Game Development Reference
In-Depth Information
Fig. 23.3
What happens
when we click on the left
arrow?
on the playing field and we click on one of the penguins. Then four arrows appear.
Because the two penguins are next to each other, one of the arrows is drawn over
the other penguin (see Fig.
23.3
). So, if we click on that arrow, what happens? Does
the selected penguin move to the left, or do we select the other penguin?
The outcome of this question depends on the order in which input is handled for
each game object. If the penguin handles the input before the penguin selector, then
the penguin selector will move to the other penguin. If the selector's
HandleInput
method is called first, then the selected penguin will move to the left. Generally,
when we develop programs, we want to be in control of the behavior of the program.
This means that we have to choose in which order we want to handle the input and
make sure that it always happens that way. In this case, the desired behavior is that
the selected penguin moves to the left. And as a general rule, we would like
objects
that are drawn on top to handle input first
. In other words, we need to call the
HandleInput
method on the objects in the list in reverse order as that they are drawn.
This can easily be done with the following
for
-instruction:
−
−−
for
(
int
i = gameObjects.Count
1; i >= 0; i
)
gameObjects[i].HandleInput(inputHelper);
As a result, objects that are drawn on top will now handle input first.
23.4 Updating Animals
Interaction between animals and other game objects is done in the
Update
method
of the
Animal
class. The main reason for doing that in the
Animal
class is because
then each animal handles its own interaction. If we add multiple animals to the
game (as we are doing here), we will not have to change anything in the code that
handles the interaction. As a first step, we do not have to update the animal if it is
not visible, or if its velocity is zero. Therefore, the first instructions in the
Update
method are: