Greetings!
New to Phaser here, porting my existing game from an ageing tech.
I’m getting trouble understanding the right “Phaser way” to declare a Scene’s instance members; Other discussion make it clear that the constructor only runs once (example).
My use case is the following:
- I’m using Phaser 3.23 with Typescript (+ Ionic, Capacitor & NgRx so TS is mandatory).
- a “control scene” is started whenever switching levels (even small rooms - so it happens quite often).
- that “control scene” adds the “content scenes” it needs with every switch, like “platformer foreground”, “platformer parallax background”, “mini-map”, “in-game hud”, etc.
First red flag in my approach:
- I have to register a “shutdown” event handler to reset variables like the mock “this.instanceVariable”.
- This, otherwise the variable retains its value from the previous scene run (see init() method).
Hence the concern:
- My platformer game allows to teleport back and forth from the foreground to the background layer.
- The platformer logic is held in a PlatformerScene.
- I must run multiple “instances” of that PlatformerScene in parallel and need them to have isolate runtime members.
So the question, how is this situation usually handled? I don’t imagine I’m doing rocket science, maybe just headed the wrong way
~
Thanks in advance for your time,
NB. The following bit of code shows the “control scene” I’m busy with.
export class ControlScene extends Phaser.Scene {
private layers: Phaser.Scene[] = [];
private mainLayer: Phaser.Scene;
private bgParallaxLayer: Phaser.Scene;
private hudLayer: Phaser.Scene;
private instanceVariable = 0; // To illustrate the "red flag", see cleanup() below
constructor() {
super({ key: "controlScene" });
}
init(data) {
this.events.on("shutdown", this.onShutdown, this);
console.log("variable: " + this.instanceVariable++);
}
create(sceneData: any) {
const { delegate } = this.plugins.get(DelegatePlugin.ID) as DelegatePlugin;
/* ... implementation ... */
}
run(sceneData: SceneSetData) {
this.scene.start("controlScene", sceneData);
}
/* ... class implementation ... */
private cleanup() {
this.layers.forEach((layer) => this.scene.remove(layer));
this.layers.length = 0;
this.instanceVariable = 0; // First red flag, this suggest "I'm not using Phaser the right way"
}
private onShutdown() {
this.cleanup();
}
}