Play Animation Once and Then Freeze on Final Frame

Hi,

I am having trouble getting the desired effect.

My code to create the animation is:

this.anims.create({
      key: 'death',
      frames: this.anims.generateFrameNames('player', {prefix: 'bof ', suffix: '.aseprite', start: 28, end: 33}),
      frameRate: 10,
      repeat: 0
  });

It is called at the end of the if statement below which is in my update method.

  if(!this.playerIsDead) {
    if (this.cursors.left.isDown)
    {
        this.player.body.setVelocityX(-200);
        this.player.anims.play('walk', true); // walk left
        this.player.flipX = true; // flip the sprite to the left
    }
    else if (this.cursors.right.isDown)
    {
        this.player.body.setVelocityX(200);
        this.player.anims.play('walk', true);
        this.player.flipX = false; // use the original sprite looking to the right
    } else {
        this.player.body.setVelocityX(0);
        this.player.anims.play('idle', true);
    }
    // jump
    if (this.cursors.up.isDown && this.player.body.onFloor())
    {
        this.player.body.setVelocityY(-400);
    }
  } else {
    this.player.anims.play('death',true);
  }

I have referred to the post https://www.html5gamedevs.com/topic/41298-how-to-not-loop-animation/. If I set the second parameter of anims.play to false, then the animation doesn’t play at all. Regardless of the repeat setting it plays infinitely so it doesn’t seem to work as described in the post I have referenced.

What I want to do is play the animation just one time and freeze on the last frame. Can someone advise?

Hi @Skeletron, since your call to sprite.anims.play() is in the game’s update method, its being run say approximately 60 times a second. This is why the repeat parameter in the animation settings is not working as it should.

Since its in the update method, try to make that piece of code execute only once, and after it gets executed block that code from execution. You can do this in lot of ways, but one easy way is to use flag variables.

this.animationPlayed = false;

if(this.animationPlayed == false) {
    this.animationPlayed = true;
    sprite.anims.play("death");
}

Hope this helps.

3 Likes

Thanks, that’s it, I called the anim play method from the callback function on the player being hit and that worked.

3 Likes