I am trying to move my sprite to forward direction.
function create(){
playMain =this.physics.add.sprite(300,400,'player1');
playMain.setCollideWorldBounds(true);
cursors = this.input.keyboard.createCursorKeys();
}
function update() {
if(cursors.up.isDown) {
this.physics.arcade.accelerationFromRotation(playMain.rotation, 300, playMain.body.acceleration);
}
if (cursors.left.isDown)
{
playMain.body.angularVelocity = -150;
}
if (cursors.right.isDown)
{
playMain.body.angularVelocity = 150;
}
}
the sprite rotates if i press left arrow key or right arrow key but as soon as i press up arrow key the sprite stops rotating and doesn’t even move? I want my sprite to move. How can I do so?
Google console says, “Uncaught TypeError: Cannot read property ‘accelerationFromRotation’ of undefined”
Now, if i press up arrow, it moves forward in random direction and the rotation of the sprite won’t stop. My problem is not solved yet. Any suggestions?
playMain is a sprite, not the scene. Use this.physics.velocityFromRotation like you used this.physics.arcade.accelerationFromRotation in your original code.
You never reset its angular velocity. Set playMain.body.angularVelocity to 0 in the final else statement. With your original code, the sprite stopped rotating because the game crashed.
In Phaser, all sprite’s textures are relative to the right side. If your sprite isn’t facing the right in the beginning, stuff like what you said happens. Try rotating your sprite to face the right in something like Photoshop.