ruk·si

🛸 Phaser
Mixins

Updated at 2024-04-17 10:49

Phaser game objects get their functionality from inheritance. However, sometimes you want to share functionality between different objects. This is where mixins come in, and this is also how Phaser works under the hood.

This is how I define mixins so:

  • you can chain mixins
  • typing works inside the mixin
  • typing works inside the class that uses the mixin
  • typing works on the instance of the class that uses the mixin
// a shared utility
export type Constructor<T = {}> = new (...args: any[]) => T

// a mixin, use the game object class that implements the features you use
export default function YellMixin<
    TBase extends Constructor<Phaser.GameObjects.Sprite>
>(Base: TBase) {
    return class Yell extends Base {
        yell(message: string) {
            console.log(`${this.name}: ${message}`);
        }
    };
}

// a sprite that uses the mixin, you can also chain mixins
export class Hero extends TileModelMixin(Phaser.GameObjects.Sprite) {
    constructor(scene: Phaser.Scene, x: number, y: number) {
        super(scene, x, y, 'hero-sprite-key');
        this.setName('Hero');
        this.scene.add.existing(this);
    }

    addedToScene() {
        this.yell('I am here to save the day!');
    }

    removedFromScene() {
        this.yell('I am out of here!');
    }
}