Game Development Reference
In-Depth Information
to manage. In this chapter, we will look at various ways to organize the code to keep
things manageable.
7.2.2 The
HandleInput
Method: Organizing Instructions in
Methods
Take a look at the
Painter3
program belonging to this chapter. A difference between
the
Painter2
program and the
Painter3
program is that the
Painter
class contains an-
other method called
HandleInput
. This method was created by the programmer of this
game, as opposed to the others, which are required by the framework in some way.
Generally, programmers define methods in such a manner that they logically divide
the instructions into related 'chunks' of instructions. By grouping our instructions
in methods, we can more easily recognize which instructions do what. A second
advantage is that if we structure these instructions in methods in a smart way, we
can reuse the same instructions in different contexts. This is what the
HandleInput
method looks like:
public void
HandleInput()
{
previousMouseState = currentMouseState;
previousKeyboardState = currentKeyboardState;
currentMouseState = Mouse.GetState();
currentKeyboardState = Keyboard.GetState();
codeforhandlingtheplayerinput
}
Inside this method, we placed all the instructions for handling player input (both
mouse and keyboard). The
HandleInput
method is then called from the
Update
method:
protected override void
Update(GameTime gameTime)
{
HandleInput();
}
Currently, the
Update
method does not do anything else, but this will change in the
later versions of the game. It is very useful to put all input handling into a separate
method, because when we need to change how the game responds to player input,
we immediately know where to look. Furthermore, we can now clearly see the dif-
ference between dealing with player input and updating the game world. Although
in the current version we do not need to update the game world in any way, a more
complicated game will need to do a lot of different things: handle collisions between
game objects, calculate speed and positions of objects, update the current score, and