Game Development Reference
In-Depth Information
Finding Game Objects
Although assigning identifiers to game objects may be a good idea, it's only useful if you also
provide a way to find these game objects. To see how this can be done, let's add a method find to
the GameObjectList class that looks through the list of game objects to see if any of them have the
requested identifier. If the game object is found, the method returns a reference to this game object;
otherwise, it returns null . The header of the method is as follows:
GameObjectList.prototype.find = function (id)
The only thing you have to do now is write the algorithm that examines the game objects in the
list and returns the game object matching the identifier, if it's contained in the list. You use a for
instruction to do this (although you could use a while instruction to do the same thing). In the for
loop, you check whether the current game object's identifier matches the requested identifier that
is passed as a parameter to the method. If so, you return that object. If you didn't return from the
method in the body of the for loop, it means none of the game objects in the list had the requested
ID, so the method returns null . The body of the find method then becomes
for (var i = 0, l = this._gameObjects.length; i < l; i++) {
if (this._gameObjects[i].id === id)
return this._gameObjects[i];
}
return null;
Note that once the return instruction is executed, you return immediately from the method. This
means the remaining game objects aren't checked anymore. Furthermore, you don't check whether
game objects have duplicate IDs. If multiple game objects carry the same ID, this method returns the
first one it finds.
Recursion
There is one thing you haven't taken into account. It is, of course, possible that one or more of the
game objects in the list is itself of the type GameObjectList . If that game object contained a game
object with the ID you seek, then the method from the previous section wouldn't find it, because that
method only checks the game objects that are stored in the list of the current object ( this ). How can
you solve this? First you need to check whether an object is an instance of a certain type. For that,
you can use the instanceof keyword:
if (someObject instanceof GameObjectList)
// do something
 
Search WWH ::




Custom Search