TIL Emitting events across code
POSTED ON:
TAGS: phaser
In Phaser 3:
You'll have multiple JS files to manage your code.
Say you had a MonsterSpawner.js
file,
and a GameScene.js
file.
- Your MonsterSpawner creates a instance of the Monster.
- The game character, the hero, destroys that instance.
- We now want another monster to be generated.
We can have that code live in the GameScene.js
(if monster is destroyed, spawn another one).
But we already identified that MonsterSpawner.js
should manage all the monsters.
How do we have GameScene.js
tell MonsterSpawner.js
to make a new monster?
By emitting!
One file emits the action to a global events area.
And the other file is listening for that moment.
When that happens, it fires the event!
// GameScene.js
this.scene.events.emit('spawnNewMonster', theMonsterObject)
// MonsterSpawner.js
this.scene.events.on('spawnNewMonster', (monster) => {
this.monsterGenerator(monster);
});
Via
https://phaser.discourse.group/t/emit-events-across-scenes/666/6
Related TILs
Tagged: phaser