Callback for when a specific animation is complete in Phaser 3?

Viewed 3654

I am creating a game with the Phaser 3 framework, and it has many animations. In my code, I already have an animation that plays (or resumes) after any animation is played, which is fine. The code for it is

 //This keeps the rolling animation going once the push animation is done
    skater.on('animationcomplete', () => {
        skater.anims.play('roll');
    });

But for the rest of the game, I need specific actions to happen once a corresponding animation is complete. Is there a function similar to the one above, where I can pass the animation's key or name as a parameter?

I am currently this example that I saw on a Phaser 3 discussion board. This is all in the create() function.

    //Animation key
    const shuvKey = 'shuv'
    //Shuvit animation
    var shuvFrameNames = this.anims.generateFrameNames(
        'sheet', {start: 9, end: 12, zeroPad: 4,
        prefix: 'shuv/'}
    );
    this.anims.create({
        key: shuvKey, frames: shuvFrameNames, frameRate: 32, repeat: 0 
    });
    skater.once(game.Animations.Events.SPRITE_ANIMATION_KEY_COMPLETE + shuvKey, function(animation, frame) {
        score += 3;         
        }, this);

But I get "Uncaught TypeError: Cannot read property 'Events' of undefined". I'm not sure if that has something to do with my game configuration, so I will post that below.

Configurations

//Configurations for the physics engine
var physicsConfig = {
    default: 'matter',
    matter : {
        gravity: {
            x: 0,
            y: 2.5, // <--This is the only way I could get the skater to roll up the ramp.
        },
        debug: true //CHANGE THIS TO TRUE TO SEE LINES
    }   
}

//Variables for height and width
var gameHeight = 750;
var gameWidth = 3000;

//Game configurations
var config = {
    type: Phaser.AUTO,
    width: 1500, //<-- this is the width of what we will see at one time
    height: gameHeight,
    physics: physicsConfig,
    scene: {
        preload: preload,
        create: create,
        update: update
    }   
}

/* This variable will be used to make sure the skater 
cannot ollie while he is already in the air */
let skaterTouchingGround;

//Start the game
var game = new Phaser.Game(config);

I need to be able to pass a function that performs will perform any following when a given animation is complete, instead of just when any animation is complete.

1 Answers

You can use the animationcomplete event to run a callback function after an animation is done:

skater.on('animationcomplete', doSomething);

doSomething = () => {
   alert('Animation finished!');
}

EDIT:

OP asked how to call different functions as callback, one way to accomplish this is like so:

skater.on('animationcomplete', doSomething);

skater.on('animationcomplete', doSomethingAgain);

doSomething = () => {
   alert('Animation finished!');
}

doSomethingAgain = () => {
   alert('Animation finished again!')
}
Related