🛸 Phaser - State Management
Updated at 2024-04-17 07:50
Scenes communicate by:
- direct method calls e.g.
this.scene.get('sceneName').doIt()
- events through the default Scene
EventEmitter
atthis.events
- events through a custom
EventEmitter
instance - values and events through
this.registry
, intended for sharing data - any other custom state paradigm like Redux, MobX, etc.
The right communication approach depends on the game, but... Using this.registry
is a good practice. Custom state management paradigms are only beneficial for games with highly complex game state and logic. The main benefit of custom paradigms is better testing and forcing separation of logic and visuals.
// the registry approach:
this.registry.set('score', 0);
this.registry.get('score');
this.registry.on('changedata', (_parent, key, data) => console.log(data), this);
// redux-in-a-nutshell:
// * Always separate 1) canonical state 2) view state and 3) edit state
// * Input triggers an action.
// * Action updates game state.
// * The action optionally triggers separate action for UI changes.
const state = getGameState()
const store = createGameStore(state)
const scene = new BootScene('BootScene', {store})