Search code examples
animationgame-physicsphaser-frameworkmatter.js

How to only play animation while a sprite is moving in Phaser 3?


I'm creating a game in Phaser 3, using the matter physics, as I've done before. A problem I've never run into until now, however, involves animations and movement. I want my animation to only play while the player is moving, and stop when he stops moving, like a player would in a real game.

I've tried all sorts of do-while loops, using "animationcomplete" and without it. I've also tried having my animation on loop (repeat: -1) and having it set to only execute once.

I DO know that, .isDown tracks the key and does the following code as long as it as pressed, versus .JustDown only executing it once. I'm not really sure which to use there either.

Code for animation

 //Animations
 //Running right animation
 var runRightFrameNames = this.anims.generateFrameNames('sheet', {
    start: 14,
    end: 16,
    zeroPad: 4,
    prefix: 'run_right/'
 })
 
 this.anims.create({
    key: 'runRight',
    frames: runRightFrameNames,
    frameRate: 1,
    repeat: 0
 })

Current code inside update() function, not the only thing I've tried

//If the right arrowkey is pressed
   if (this.arrowKeys.right.isDown) {
      //Move player
      this.hero.setVelocityX(5);
      //Play animation
      this.hero.anims.play('runRight');
      //When animation is done, stop hero
      this.hero.on("animationcomplete", () => {
      this.hero.setVelocityX(0);
   });
}

Solution

  • You can modify your code snippet like this:

    //If the right arrowkey is pressed
    if (this.arrowKeys.right._justDown) {
        console.log('Cursor right is pressed!');
        
        //Move player
        this.hero.setVelocityX(5);
     
        //Play animation
        this.hero.anims.play('runRight');
    
    } else if (this.arrowKeys.right._justUp) {
        console.log('Cursor right is NOT pressed!');
    }
    

    EDIT:

    To fix the hero's animation change this line this.hero.anims.play('runRight'); to this.hero.anims.play('runRight', true);

    You should also change the repeat value to -1 like so:

    this.anims.create({
        key: 'runRight', frames: runRightFrameNames, frameRate: 6, repeat: -1
    });