Game Development Reference
In-Depth Information
This will work fine but it's not ideal in larger games. For one, you are simply adding this behavior to each instance
of the shape object. If you decide you need more orbs in the future, you will need to repeat the process of adding the
new properties and methods. Granted, you could probably build some sort of spawn function to handle this, but
diving into a function to further build onto these new attributes is not a very elegant way to program. Ideally, you can
build an entirely new custom Orb object that can be instantiated and added to your game.
Extending EaselJS
By creating new objects that extend EaselJS display objects, you can carry on using them as you have on the stage in
your game, plus give them new, unique properties. These objects will contain encapsulated logic that is completely
unique and extracted from your game code.
Using the proceeding orb example, let's look at how you could add new orbs to your game. The following example
demonstrates the use of a custom Orb class:
var orb = new Orb();
stage.addChild(orb);
An instance of the class Orb is created and added to the stage. Its properties and methods are created within its
declaration, which can be located in a separate file, which makes it much more manageable. No longer do you need to
pollute your game logic space by creating dynamic attributes.
So how is this accomplished? Take a look at Listing 8-1, which shows the template code, which will be used for
extending all EaselJS classes in this topic.
Listing 8-1. Code Template for Extending Shape
(function() {
var Orb = function() {
this.initialize();
}
Orb.prototype = new createjs.Shape();
Orb.prototype.Shape_initialize = Orb.prototype.initialize;
Orb.prototype.initialize = function() {
this.Shape_initialize();
}
window.Orb = Orb;
}());
Before diving into the code for Orb , take a look at what it is surrounded in. The code is within an immediate
function, which is a function that executes only once, and immediately. This assures you that you are out of the global
space when writing the logic to create the new class. A function named Orb is then created, which is the actual object
you are writing. This function is known as the object's constructor function and is called immediately when you make
a new instance of Orb . This function calls its initialize method, which we will go over shortly.
After the constructor function, which is what declares the Orb class, its prototype is set to a new Shape . This is how
you inherit all of the shape's properties and methods. At this point, Orb is essentially a carbon copy of Shape . Next, the
initialize method on Shape needs to be overridden so the new, custom shape will be called on instantiation. This is
done by assigning it to a property on Orb so you can access it later during your own initialize function.
 
Search WWH ::




Custom Search