I’m working on animating a character (using a texture atlas) with user input in Phaser 3 and I’m running into an issue with the animation not stopping when I release the respective arrow button. I’ve tried a few tactics, and some of them only partially work. The code below is what I use which works as intended in all respects, except the animation doesn’t stop after I release the respective arrow key. Maybe I need logic with stopping animation once the key is lifted? Any suggestions? Thanks!
I’ve used this post as an example, but it prevents the character from moving diagonally:
Sprite Sheet animation with arrow keys
update() {
this.hero.setVelocity(0,0);
if (this.cursors.up.isDown) {
this.hero.anims.play('walkUp', true);
this.hero.setVelocityY(-200);
}
else if (this.cursors.down.isDown) {
this.hero.anims.play('walkDown', true)
this.hero.setVelocityY(200);
}
if (this.cursors.left.isDown) {
this.hero.anims.play('walkLeft', true)
this.hero.setVelocityX(-200);
}
else if (this.cursors.right.isDown) {
this.hero.anims.play('walkRight', true)
this.hero.setVelocityX(200);
}
}
2
Answers
Well, through more research, I found out and answer. Basically, I separated the movement logic from the animation logic. This youTube video shows the troubleshooting involved starting around minute 9: https://www.youtube.com/watch?v=H-a_-uuM26E
Here's my final code that works:
There are many ways to solve this. Your solution is ofcourse vaild, but here two alternative, the would keep your code abit shorter an easier to read.
Alternative 1
Since movement to the left and right override the up and down movement you could simply reorder the
if/else
blocks and chain them all as ob bigif/else
block and stop the animation in the finalelse
. (Me from the future, yourif's
only override the animation)Alternative 2
Just check at the end of the
update
function, if thevelocity
-length is more or less equal to zero. (Since the object often don’t really stop (because of gravity, gliding and some physics round stuff )< 2
should be save/okay to use)In personally like the first altertive, but depending on your usecase, if you need to handle up/down and left/right independently, the later should be fine also.