Supporting Components

The last core piece of functionality necessary to bootstrap Quintus is adding in component support. As described earlier in the section “Using Inheritance in Game Engines,” components make it simpler to create small pieces of reusable functionality that can be mixed and matched among the various sprites and objects that need it.

Crafty.js a popular, mature HTML5 Game engine based entirely around a component-entity architecture, as discussed in Chapter 26, “Using an HTML5 Game Engine,” and was the inspiration for the Quintus component methods.

Designing the Component API

As usual, think about the API first and how you want to use components in the game. Components need to be added and removed from sprites quickly and concisely. They should be accessible from the objects but also not overly pollute the object’s namespace. Listing 9-13 shows and example of how you could define and use components.

Listing 9-13: Imagining a component system

var exGame = Quintus(); var player = new exGame.GameObject(); exGame.register('sword',{ added: function() { // When whatever we are registered with triggers // a fire event, call the attack method this.entity.bind('fire',this,'attack'); }, attack: function() { // Code to attack }, // Methods copied directly over to the entity extend: { attack: function() { this.sword.attack(); } } }); // Add the sword component player.add('sword'); // Calls attack via event player.trigger('fire'); // Call attack directly from extended event ...

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.