Home > database >  How can I stop animation loop, but not mid-animation in Phaser 3?
How can I stop animation loop, but not mid-animation in Phaser 3?

Time:03-08

I have an animation, which usually is supposed to play 3 times, thus the config currently says repeat: 2. However, under a certain condition (the player stops dragging an element) I want the animation to finish and stop without repeating.

By that I mean I don't want it to stop right at the frame it is at the second, but I want it to finish playing to the last frame I assigned in frames and then stop before it repeats.

How would I be able to do this?

// ANIMATION CREATED HERE
this.anims.create({
        key: "nom",
        frameRate: 12,
        frames: this.anims.generateFrameNames("chara", {
            prefix: "nom_000",
            start: 0,
            end: 4}),
        repeat: 2,
    });

this.input.on('drag', (activePointer, gameObject, dragX, dragY) => {
    gameObject.x = dragX;
    gameObject.y = dragY;
        
    if(Phaser.Geom.Intersects.RectangleToRectangle(gameObject.getBounds(), character.mouth.getBounds())) {  
        gameState.snack_cursor.play("fries_cursor", true);

        // ANIMATION PLAYED HERE
        character.sprite.play("nom", true); 
    }
});

this.input.on('dragend', (pointer, gameObject, dragX, dragY) => {
    if (gameObject.anims.isPlaying)
        gameObject.anims.stop();

    // ANIMATION STOPS HERE, BUT CURRENTLY AT WHATEVER FRAME IT'S AT
    if (character.sprite.anims.isPlaying)
        character.sprite.anims.stop();
});

CodePudding user response:

You can use the function stopAfterRepeat (documentation).
Just call it with the parameter 0, and the current animation will be finished, before the animation is stopped. I think this is what you are after.

 ...
 character.sprite.anims.stopAfterRepeat(0);
 ...
  • Related