Events & Communication

Headers: Core/include/Core/EventBus.h, Core/include/Core/Events.h

EventBus

The engine provides a publish/subscribe event system for communication between behaviors and systems:

auto &bus = engine.GetEventBus();

Subscribing to Events

void OnStart(flecs::entity e, Engine &engine) override {
  auto &bus = engine.GetEventBus();

  m_SubId = bus.Subscribe<KeyEvent>([this](const KeyEvent &evt) {
    if (evt.key == GLFW_KEY_P && evt.action == GLFW_PRESS) {
      m_Paused = !m_Paused;
    }
  });
}
Warning

Store the SubscriptionID and unsubscribe when the behavior is destroyed to avoid dangling callbacks.

Publishing Events

// Immediate delivery
engine.GetEventBus().Publish(MyCustomEvent{42, "hello"});

// Queued (processed on next Flush)
engine.GetEventBus().Queue(MyCustomEvent{42, "hello"});

Built-in Events

EventFieldsWhen Fired
WindowResizeEventint width, heightWindow resized
KeyEventint key, action, modsKey press/release
MouseMoveEventdouble x, y, deltaX, deltaYMouse moved
MouseButtonEventint button, action, modsMouse button click
MouseScrollEventdouble xOffset, yOffsetScroll wheel

Custom Events

Define your own event structs for behavior-to-behavior communication:

// Define in a shared header
struct DamageEvent {
  uint64_t targetId;
  float amount;
};

// Publisher (e.g., weapon behavior)
engine.GetEventBus().Publish(DamageEvent{enemy.id(), 25.0f});

// Subscriber (e.g., health behavior)
bus.Subscribe<DamageEvent>([this, e](const DamageEvent &evt) {
  if (evt.targetId == e.id()) {
    m_Health -= evt.amount;
  }
});

EventBus API

MethodDescription
Subscribe<T>(callback)Register a handler, returns ID
Unsubscribe(id)Remove a subscription
Publish<T>(event)Deliver immediately to all subscribers
Queue<T>(event)Queue for delivery on next Flush()
Flush()Process all queued events