Game Development Reference
In-Depth Information
procedure needs to be followed if the HandleInput method is called or if the Update
method is called. For example, the only instruction that is inside the HandleInput
method is
foreach (GameObject obj in gameObjects)
obj.HandleInput(inputHelper);
So, GameObjectList itself does not define any behavior, it simply manages the be-
havior of the game objects it contains. Similarly, the Update method simply calls
the Update method of all the game objects in the list. Note that we used the foreach -
instruction for convenience. For HandleInput and Update , we do not care in what order
the game objects handle their input or update themselves. For the Draw method, we
have to do it slightly differently, since we want to draw the game objects with the
lowest layer number first.
This means that we cannot use the foreach loop here, because it does not allow
us to control the order in which the elements of a collection are traversed. The most
robust way to do it would be to sort the list of game objects in the beginning of each
call to the Draw method. After that, we can use a regular for -loop to draw the game
objects one after the other, according to their ordering inside the list. The body of
the Draw method would then look something like this:
sortthelistofgameobjects
...
for ( int i = 0; i<gameObjects.Count; i++)
gameObjects[i].Draw(gameTime, spriteBatch);
Because sorting can be quite complex, we will use another technique that is a bit
less robust, but also much faster, since we do not have to perform a sorting operation
every time we want to draw the objects. For this, we are going to write a very smart
Add method in our GameObjectList class. We are going to write this method in such
a way that we can ensure that, after this method has added the game object to the
list, the list is already sorted! This can be done by putting the game object in the
list at the right location. So, if the list contains three objects at layer 0, and two at
layer 3 and we want to add a game object at layer 1, we insert this object between
the objects at layer 0 and the objects at layer 3.
To make things easy for us, the List class already has a method called Insert which
can insert an object at a certain index of the list. In order to achieve this behavior, we
construct a for -instruction that walks through the list. If we arrive at a point where
the current object has a layer with a higher number than the object that we want to
add, we insert the object. This for -instruction is given as follows:
for ( int i = 0; i < gameObjects.Count; i++)
if (gameObjects[i].Layer > obj.Layer)
{
gameObjects.Insert(i, obj);
return ;
}
Search WWH ::




Custom Search