How to stop animations when a sprite's movement stops in Phaser 3
Posting this to share how I tackled this problem. I had searched everywhere and couldn't seem to find a working solution.
The problem (my version) - I had a sprite that was going to be my player in my game. I had both a running left and a running right animation. These animations are set to loop, so the player will appear as if they are running when their velocity is increased. I wanted the player's animation to stop once they had stopped moving
Solution 1:
My implementation
update() {
//If right arrowkey is pressed
if (this.arrowKeys.right._justDown) {
//Move player
this.hero.setVelocityX(5);
//Play your animation animation
this.hero.anims.play('yourAnim', true);
};
//This will run every time the animation "repeats", meaning it has gone through all of its frames. Make sure your animation is set to loop!
this.hero.on("animationupdate", () => {
//If the player has stopped moving
if (this.hero.body.velocity.x < 0.5 && this.hero.body.velocity.x > -0.5) {
//Stop the animation
this.hero.anims.stop();
}
});
}
Formatting is a little bad. And there's almost surely a slightly quicker way to do this. But this is my implementation for now, and I just wanted to share in case someone else was having the same issue! Feel free to comment with a better solution, or any questions
Solution 2:
I had a problem like this, you might not need a solution anymore, but others might. I used JustDown to start the animation and JustUp to go to my idle state. Code in update:
if(Phaser.Input.Keyboard.JustDown(downKey)){
gamePiece.anims.play("down");
}
if(Phaser.Input.Keyboard.JustUp(downKey)){
gamePiece.anims.play("spin");
}
In your case, it would stop the animation instead of an idle animation.