Game Development Reference
In-Depth Information
In order to ensure that we insert the object only once, we return from the method
after inserting the object. However, we are not done yet. What happens if the list
does not contain any objects, or if it contains only objects with a lower layer number
than the layer number of the object we want to add? In these cases, the condition in
the
if
-instruction will never be
true
, so the game object will not be added at all. This
is not what we want. If we reach the end of the
for
-instruction without having added
any object, we
still
want to add the object to the list, but then we can simply add it
at the end. Therefore, we add the following instruction after the
for
-loop:
gameObjects.Add(obj);
Now, there is still one thing to do. When a game object is added to the list, it means
that the list object should become its parent. So we have to add the following in-
struction as well:
obj.Parent =
this
;
This instruction is the
first
instruction of the
Add
method, because then we are sure
that the parent will always be properly set, whether the game object is inserted
somewhere in the list or added at the end. The complete
Add
method is shown in
Listing
14.2
. Because we ensure that the game objects are added at the right po-
sitions, the
Draw
method simply consists of a
for
-loop (also see Listing
14.2
). But
why did we say that this version was slightly less robust than sorting the game list
at every call of the
Draw
method? Imagine the following code fragment:
SpriteGameObject obj1 =
new
SpriteGameObject(spr, 1);
SpriteGameObject obj2 =
new
SpriteGameObject(spr, 2);
GameObjectList objects =
new
GameObjectList();
objects.Add(obj1);
objects.Add(obj2);
obj2.Layer = 0;
In this fragment, we create two sprite game objects, and add them to a list of game
objects. The
Add
method call makes sure that they are added at the right position (in
this case, the order of adding happens to coincide with the layer ordering). However,
after that we change the layer index of object
obj2
, but the list of game objects is not
changed, meaning that
obj1
will still be drawn before
obj2
. A way to solve this would
be to change the
Layer
property of a game object so that it removes itself from its
parent and adds itself again. However, there are no guarantees that any subclasses of
the
GameObject
class that override this property will remember to take care of this.
So, the system is clearly less robust. However, it is a lot faster, and we do not have to
bother writing a sorting algorithm (although this is easier than you think, especially
with the collection classes of C#).
For the sake of completeness, the
GameObjectList
class also contains a
Remove
method. This method is a lot simpler than the
Add
method. It removes the object