Game Development Reference
In-Depth Information
Before the instanceof keyword, you put the object to be checked; and after the keyword you place
the type. If the object is of the given type, then the expression yields true . If not, the result is false .
Therefore, you can use it in an if instruction as in the previous example. If you know the object is of
type GameObjectList , you can try to find the game object you're looking for in the game-object list
represented by that object. The following code does exactly that:
for (var i = 0, l = this._gameObjects.length; i < l; ++i) {
if (this._gameObjects[i].id === id)
return this._gameObjects[i];
if (this._gameObjects[i] instanceof GameObjectList) {
var list = this._gameObjects[i]._gameObjects;
for (var i2 = 0, l2 = list.length; i2 < l2; ++i) {
if (list[i2].id === id)
return list[i2];
}
}
}
return null;
So, now you check for each game object to determine whether it's of type GameObjectList . If so, you
traverse that list's _ gameObjects variable and look for the game object in there.
Are you finished now? Well, not really. What if one of the game objects in list is of type
GameObjectList ? It means you have to add another layer that checks whether one of the game
objects in that list perhaps corresponds to the ID you're looking for. But one of those game objects
could also be of type GameObjectList . Obviously, this approach isn't ideal. However, you can do
something to avoid this kind of infinite-search problem. Why not use the find method again? Look at
the following code:
for (var i = 0, l = this._gameObjects.length; i < l; ++i) {
if (this._gameObjects[i].id === id)
return this._gameObjects[i];
if (this._gameObjects[i] instanceof GameObjectList) {
var obj = this._gameObjects[i].find(id);
if (obj !== null)
return obj;
}
}
return null;
This code may look a bit strange. You're actually calling the method that you're currently writing. Why
does this work? Think about what is happening when the find method is called on an object. If the
game object you're looking for is in the list, then this method returns that object. Furthermore, the
method calls the find method on every object that is also of type GameObjectList . If none of those
method calls finds the object, the method returns null . And each of the find method calls also calls
the find method on the objects that belong to it that are of type GameObjectList . This big tree of find
method calls ends when you reach the bottom of the game-object hierarchy. In other words, at some
point there are no more lists: only game objects. Then the results of all the find method calls (each of
Search WWH ::




Custom Search