简体   繁体   中英

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

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

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.

I think you're looking for the .pause() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM