Supporting Events

Adding support for events in a game engine makes it easier to keep different parts of the engine from becoming too tightly coupled. It means one part of the game can communicate events and actions to other parts of the game without needing to know anything about the objects it’s communicating with.

When you add components into the mix, it even allows a sprite to communicate with itself without needing to know all the components that make it up. A Physics component on a sprite might trigger a collision event, and two components listening for the event could separately handle triggering the appropriate sound effect and animation effect.

Designing the Event API

Quintus uses a base class called Evented that is the jumping-off point for any object that needs to subscribe to and trigger events. As usual, you must think about the API first and then build the code around that API afterward.

Given a player sprite and a scene object, now walk through an example event functionality:

// Play the intro animation on the player 
// when the scene starts
scene.bind('start',player,function() {
  this.showIntro();
});

// Bind a method on player using the method name
scene.bind('finish',player,'showFinal');

// Trigger the start event on the scene
scene.trigger('start');

// Unbind the player from the start event
scene.unbind('start',player);

// Release the player from listening
// to all events (such as if it's blown up)
player.debind();

This API provides a way to bind, trigger, and ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.