Game Development Reference
In-Depth Information
Because you ensure that the game objects are added at the right positions, the draw method simply
consists of a for loop:
GameObjectList.prototype.draw = function () {
if (!this.visible)
return;
for (var i = 0, l = this._gameObjects.length; i < l; ++i)
this._gameObjects[i].draw();
};
This way, your drawing operation stays very efficient because you don't sort the list of game objects
every time! There is a slight disadvantage to doing it this way, though. Consider the following code
fragment:
var obj1 = new SpriteGameObject(spr, 1);
var obj2 = new SpriteGameObject(spr, 2);
var objects = new GameObjectList(0);
objects.add(obj1);
objects.add(obj2);
obj2.layer = 0;
This fragment creates two sprite game objects and adds them to a list of game objects. The add
method call makes sure they're added at the right position (in this case, the order of adding happens
to coincide with the layer ordering). However, after that you change the layer index of object obj2 ,
but the list of game objects isn't changed, meaning obj1 will still be drawn before obj2 . As a result,
it's possible to break the system. In this case, clear documentation that instructs the developer not
to do such nasty things is highly recommended! You could, for example, add a warning comment
above the definition of the add method in which you tell the user that only the current layer values
of the objects are taken into account. Another option is to add a comment to the layer variable
declaration that says when the layer is changed, the drawing order isn't automatically updated. A
better, more robust way to deal with this is to add a property through which the layer is changed,
which automatically sorts the drawing order of the parent the object belongs to.
For the sake of completeness, the GameObjectList class also contains a few other useful methods.
The clear method removes all game objects from the list. The remove method removes an object
from the list; and because the object isn't part of the list anymore, its parent is set to null .
You can now profit from the layered drawing mechanism you've created, as well as the hierarchical
structure. To make your code clearer, you can define a few different layers as a variable (see
JewelJam.js for the complete code):
var ID = {};
...
ID.layer_background = 1;
ID.layer_objects = 20;
 
Search WWH ::




Custom Search