Example using Phaser sprite events.
import * as Phaser from 'phaser';
enum ImageKey {
Character = 'Character',
}
enum CharacterAnimationKey {
Collect = 'Collect',
Idle = 'Idle',
WalkRight = 'WalkRight',
WalkLeft = 'WalkLeft',
}
type TCharacterAnimationKey = keyof typeof CharacterAnimationKey;
type TCharacterAnimationValue = { start: number; end: number };
const CharacterAnimations: { [key in CharacterAnimationKey]: TCharacterAnimationValue } = {
Collect: { start: 0, end: 3 },
Idle: { start: 4, end: 7 },
WalkLeft: { start: 8, end: 11 },
WalkRight: { start: 12, end: 15 },
};
export default class Character extends Phaser.Scene {
Character: Phaser.Types.Physics.Arcade.SpriteWithDynamicBody = null!;
constructor() {
super({ key: 'ExampleScene' });
}
preload = () => {
this.load.spritesheet(ImageKey.Character, 'assets/image_spritesheet_character.png', {
frameWidth: ConfigContent.SpritesheetSize / 1,
frameHeight: ConfigContent.SpritesheetSize / 1,
});
};
create = () => {
this.Character = this.physics.add.sprite(ConfigContent.Width / 2, 0, ImageKey.Character);
Object.entries(CharacterAnimations).forEach((CharacterAnimation) => {
const [key, config] = CharacterAnimation as [CharacterAnimationKey, TCharacterAnimationValue];
const singleAnimation: TCharacterAnimationKey[] = ['Collect'];
const repeat = singleAnimation.includes(key) ? 1 : -1;
this.anims.create({
key,
frames: this.anims.generateFrameNumbers(ImageKey.Character, config),
skipMissedFrames: true,
repeat,
frameRate: ConfigContent.SpritesheetFramesPerSecond / 1,
});
});
this.Character.on('animationcomplete', (animation: Phaser.Animations.Animation, frame: Phaser.Animations.AnimationFrame) => {
this.emit('animationcomplete_' + anim.key, animation, frame);
}, this.Character);
this.Character.on('animationcomplete_${CharacterAnimationKey.Collect}', (animation: Phaser.Animations.Animation, frame: Phaser.Animations.AnimationFrame) => {
console.log(animation, frame);
});
}
}