![]() |
ImagoEngine
A C++ 2D game engine built on a sparse-set ECS, with scenes, scheduled systems, events, and action-based input
|
Let subscribed systems react to things that happen without knowing about each other.
Use this when one or multiple parts of your game need to respond to something another part did: a player dying, and item being picked up, a level being finished, ect.
Include: Imago/Engine/Scene.hpp
An event is a plain struct describing (providing data for) something that happened. A system emits an event, and every system subscribed to that event type is called with it right away. Systems that subscribe to events (instead of being called every frame) are called subscribed systems and have the following signature:
See Systems
The system that emits the event does not know who is listening, and the listeners do not know who emitted it. That keeps your system decoupled. You can add a new reaction to an event without touching the code that emits it.
Each scene has its own Broadcaster that handles this. In on_load, use the scene’s _broadcaster member to subscribe to events, in a system, use ctx.broadcaster to emit events.
Events are plain data structs. Put in whatever data the listeners will need to know:
NOTE: If subscribed systems that do not need any data all simply did not receive an event struct, the Broadcaster would have know way of knowing which event is which. For this reason, even when the subscribed system does not need any data, an event struct must still be defined, it can be left empty.
In most cases subscribe in your scene’s on_load so your listeners are ready before the first frame. Subscribe with the syntax _broadcaster.subscribe<EventType>(SubscribedSystemName):
Emit from any system, with ctx.broadcaster->emit(EventType{data}). The event type is worked out from what you pass in:
Any number of systems can subscribe to the same event. They are called in the same order they subscribed:
A listener can emit another event. It is handled immediately, before the first listener continues:
| Function | What it does | Notes |
|---|---|---|
| subscribe<T>(system) | Calls system whenever a T is emitted | Subscribing twice does nothing |
| unsubscribe<T>(system) | Stops calling system for T | Warns if it wasn't subscribed |
| emit(event) | Calls every subscriber to the event's type | Immediate; in subscription order |
| clear() | Removes every subscriber |