Game Development Reference
In-Depth Information
So, GameObjectList itself doesn't define any behavior; it simply manages the behavior of the game
objects it contains. For the update method, you don't care about the order in which the game objects
update themselves. For the draw method, you do care, because you want to draw the
game objects with the lowest layer numbers first. The most robust way to do this is to sort the list
of game objects at the beginning of each call to the draw method. After that, you can use a for loop
to draw the game objects one after the other, according to their ordering in the list. The body of the
draw method looks something like this:
if (!this.visible)
return;
// sort the list of game objects
...
for (var i = 0, l = this._gameObjects.length; i < l; ++i)
this._gameObjects[i].draw();
Because sorting can be quite complex, you do it not when you draw the game objects (which has to
happen 60 times per second), but when you add game objects to the list. That way, you only sort the
list of game objects when necessary. Sorting an array in JavaScript is really easy. Arrays have a sort
function you can call. For example:
var myArray = ["named", "must", "your", "fear", "be", "before", "banish", "it", "you", "can"];
myArray.sort();
/* myArray now refers to ["banish", "be", "before", "can", "fear", "it", "must", "named", "you",
"your"]; */
By default, the sort function sorts an array alphabetically. However, what happens if you have an
array that contains more complex things than strings, such as game objects? In that case, you can
provide sort with a sorting function as a parameter. This function should indicate the ordering of any
two objects in the array. You can write this function yourself. For example, here is a call to the sort
function that orders the game objects according to their layer:
this._gameObjects.sort(function (a, b) {
return a.layer - b.layer;
});
When the sorting function returns a positive number, a is “larger” than b and should be placed after
b , and vice versa. You can write a method called add that adds a game object to the list and then
sorts the list. This method also assigns the game-object list as the parent of the game object you
add. Here is the complete method:
GameObjectList.prototype.add = function (gameobject) {
this._gameObjects.push(gameobject);
gameobject.parent = this;
this._gameObjects.sort(function (a, b) {
return a.layer - b.layer;
});
};
 
Search WWH ::




Custom Search