Hello there, I’m trying to add this function to my character.
The idea is to rotate the weapon with the movement of the mouse.
I therefore created a group that contains players without weapon and weapon.
I’ve been looking for a solution and trying for days … but maybe I’m doing something wrong.
var game = new Phaser.Game(config);
var player;
var cursors;
var gun;
var playerWithWeapon;
function preload() {
this.load.image('bg', 'assets/bg.png');
this.load.spritesheet('gun', 'assets/gun.png', {
frameWidth: 438,
frameHeight: 198
});
this.load.spritesheet('player', 'assets/playernogun.png', {
frameWidth: 384,
frameHeight: 617
});
}
function create() {
background = this.add.image(600, 400, 'bg');
player = this.add.sprite(300, 300, 'player');
player.setScale(0.1);
gun = this.add.sprite(300, 305, 'gun').setOrigin(0.6, 0.4);
gun.setScale(0.1);
playerWithWeapon = this.physics.add.group();
playerWithWeapon.add(player);
playerWithWeapon.add(gun);
cursors = this.input.keyboard.createCursorKeys();
}
function update() {
if (cursors.left.isDown) {
playerWithWeapon.setVelocityX(-160);
//full.setFlipX(false);
} else if (cursors.right.isDown) {
playerWithWeapon.setVelocityX(160);
//full.setFlipX(true);
} else {
playerWithWeapon.setVelocityX(0);
}
if (cursors.up.isDown) {
playerWithWeapon.setVelocityY(-160);
} else if (cursors.down.isDown) {
playerWithWeapon.setVelocityY(160);
} else {
playerWithWeapon.setVelocityY(0);
}
}
I’ve created a container instead of a group, then I added physics since I want to move the player but I got this error in the console:
Uncaught TypeError: playerWithWeapon.setVelocityX is not a function
update func
if (cursors.left.isDown) {
playerWithWeapon.setVelocityX(-160);
//full.setFlipX(false);
} else if (cursors.right.isDown) {
playerWithWeapon.setVelocityX(160);
//full.setFlipX(true);
} else {
playerWithWeapon.setVelocityX(0);
}
Hello,
The point here is that you need to listen for mouse move event on the board and change you character angle depends on the cursor coordinates.
On the function which you’re trying to add the character is this.sprite = this.add.sprite(400,300,'sprite').setOrigin(0.5);
then listener for mouse move: this.input.on('pointermove', f, this);
and f is checks the coordinates and turn the character:
var angle = Phaser.Math.RAD_TO_DEG * Phaser.Math.Angle.Between(this.sprite.x, this.sprite.y, pointer.x, pointer.y);
this.sprite.setAngle(angle);
On your solution, you have a keyboard keys to turn the character, probably it also could be done in that way.
the setVelocityX, or setVelocityY will move your character, but not turn it.
To turn the character you could change the sprite picture, this could be done with this.sprite.anims.play('turnRight');
The turnRight should be first declared under create() part: