Knowledge.ToString()

Callback for Specific Animation Completion Event in Phaser 3

In Phaser 3, you can define animation for a sprite. It is possible that you want to know when the animation will be completed. Phaser 3 provides a rich set of callback functions including animation completion event. If there is only a single animation defined for a sprite, you can use any of the following solutions. But if you have more than one animations defined for a sprite, you may want to use callback for a specific animation completion event. Here is a working example.

Define Sprite Animation

In Loader scene, you would define the sprite animation using following code. Typically I define the animation in Loader Scene once all the assets are loaded. But you are free to define the animation anywhere. Please keep in mind that animation definition is global so you must define it only once.

export class LoaderScene {
    constructor() {
        super({
            key: "loader"
        });
    }
    create() {
        // define player animation
        this.anims.create({
            key: "player-jump",
            frames: this.anims.generateFrameNumbers("player", { start: 0, end: 6 }),
            frameRate: 8,
            repeat: 0
        });
    
        this.anims.create({
            key: "player-walk",
            frames: this.anims.generateFrameNumbers("player", { start: 14, end: 20 }),
            frameRate: 8,
            repeat: 0
        });
    }
}

Here I have defined two animation keys – player-jump and player-walk.

Subscribe to Any Animation Completion Event

If you want to get callback notification when any animation is complete, use the following code.

gameobj.on(Phaser.Animations.Events.ANIMATION_COMPLETE_KEY, function () {
	console.log(`animation completed`);
}, this);

In this code, callback will be called when jump and walk animation is completed.

Subscribe to Specific Animation Completion Event

If you want to get callback notification for a specific animation like jump animation completed, use the following code.

gameobj.on(Phaser.Animations.Events.ANIMATION_COMPLETE_KEY + "player-jump", function () {
	console.log(`Jump animation completed`);
}, this);

As you can see in the above code, Phaser emits the event with key Phaser.Animations.Events.ANIMATION_COMPLETE_KEY + YOUR_ANIMATION_KEY. This way you can easily get notified.

Share

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *