Skip to content

Instantly share code, notes, and snippets.

@SiegeSailor
Created March 8, 2021 03:10
Show Gist options
  • Save SiegeSailor/bfa88d8c08616a33f476c7f7adc9c2f8 to your computer and use it in GitHub Desktop.
Save SiegeSailor/bfa88d8c08616a33f476c7f7adc9c2f8 to your computer and use it in GitHub Desktop.
Example using Phaser sprite events.

Overview

Example using Phaser sprite events.

Example

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);
      });
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment