I can't move my sprite with accelerationFromRotation

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”

this.physics.arcade.accelerationFromRotation is Phaser 2 code. The Phaser 3 equivalent is this.physics.velocityFromRotation.

1 Like

It doesn’t work either for me.

Instead I tried ,

if(cursors.up.isDown) {
	//playMain.physics.velocityFromRotation(playMain.rotation, 300, playMain.body.acceleration);
	playMain.setVelocity(Math.cos(playMain.rotation) * 600, Math.sin(playMain.rotation) * 600); 
} 
else if (cursors.left.isDown)
{
    playMain.body.angularVelocity = -150;
} else if (cursors.right.isDown)
{
    playMain.body.angularVelocity = 150;
}else {
    playMain.setAcceleration(0);
    playMain.setVelocity(0,0);   // 2

}

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.

1 Like

Thanks, yeah it works. But the sprite doesn’t move towards the required point when i press up arrow rather it moves towards one side?

.Screenshot_1

Take a look at this example:
Asteroids

Okay, Is there any way that I can target the upper arrow of my sprite?

Screenshot_1

Because I think this.physics.velocityFromRotation(playMain.rotation, 200, playMain.body.acceleration) targets the right side of my sprite?

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.

2 Likes

okay thanks for the help