Events and listeners
An event says something happened: a unit died, a unit entered an area, a wave was beaten. Events go out at the end of the tick, and listeners hear them. A listener can't change what happened; to do that, use a hook.
Quick start
import { defineListener, entityDied } from '@v12-engine/engine'
export const said = defineListener({
event: entityDied,
id: 'mygame.said',
run(world, { entity }) {
world.log.info('deaths', 'a unit died', { entity: entity.id })
}
})Put it in Rules.listeners.
Common tasks
Send an event of your own
const invaderThrough = defineEvent<{ entity: EntityId }>({ id: 'td.invaderThrough', replicate: 'everyone' })
const loseLife = defineListener({ event: invaderThrough, id: 'td.loseLife', run: (world, { entity }) => { /* ... */ } })
// Rules: events: [invaderThrough], listeners: [loseLife]
world.events.emit(invaderThrough, { entity: unit.id })Don't subscribe the rules with world.events.on from outside. List listeners in Rules.listeners, so every machine and every loaded save has them.
Watch an area
const gate = defineArea({ id: 'td.gate', shape: { kind: 'circle', x: 40, z: 10, radius: 6 } })
// Rules: areas: [gate]; listen to 'enteredArea' and 'leftArea'
world.areas.inside('td.gate') // who is in it nowTo ask who is in an area and also meets some conditions, use world.query({ area: 'td.gate', is: 'enemy', of: 1 }) (Querying the world).
Show an event on the screen
replicate: 'everyone', or (payload, view) => boolean, sends an event in those players' snapshots. Payloads must be plain data, with entities by id. The view hears them in GameView.on (viewListener(key, (payload, client) => ...)), and renderers in changes.events (isGameEvent(event, key)).
Reference
Hooks vs events
| Hook | Event | |
|---|---|---|
| Runs | In the middle, before it is settled | At the end of the tick |
| Can change it | Yes | No |
| Order | By priority | The order listeners were given |
| For | The rules | Reacting: rules, screen, sounds |
Events on the screen
Packs tell of engine events with replicateEvent(healed, 'heal', (heal, view) => ...) in GamePack.replications, and add snapshot parts in GamePack.snapshotFields.
Areas
defineArea({ id, shape }) in Rules.areas: the enteredArea and leftArea events, world.areas.inside(id) and world.areas.contains(id, entity). Areas are saved with the world. world.find({ owner, type, area }) lists the living entities that match.