Game Development Reference
In-Depth Information
jects are the background, and the cannon. Both of these objects need to be drawn,
but they do not need to be updated in this example. However, for the Cannon ob-
ject, we need to handle some player input. Since this is a task relevant only for the
cannon, let us add a HandleInput method to the Cannon class that handles any input
relevant for a cannon object. In order to be able to handle input, the cannon object
needs the instance of the InputHelper class. So, we pass this as a parameter. Then,
inside the HandleInput method, we check if the player has pressed the R, G, or B key
and we update the color and angle of the cannon:
public void HandleInput(InputHelper inputHelper)
{
if (inputHelper.KeyPressed(Keys.R))
Color = Color.Red;
else if (inputHelper.KeyPressed(Keys.G))
Color = Color.Green;
else if (inputHelper.KeyPressed(Keys.B))
Color = Color.Blue;
double opposite = inputHelper.MousePosition.Y
position.Y;
double adjacent = inputHelper.MousePosition.X
position.X;
angle = ( float )Math.Atan2(opposite, adjacent);
}
For handling input in the game world, we add a HandleInput method to the
GameWorld class. This method basically tells all the game objects to handle their in-
put using the inputHelper object, therefore this method also has a parameter for pass-
ing this object. Since the only game object that deals with player input is the cannon,
we only need to call that object's HandleInput method. This is what the HandleInput
method in the GameWorld class looks like:
public void HandleInput(InputHelper inputHelper)
{
cannon.HandleInput(inputHelper);
}
In a very similar way, we may need to update all the game objects. For that, we add
an Update method to the GameWorld class. Since there are no objects yet to update,
we leave this method empty for now.
Both the HandleInput and Update methods in the GameWorld class are called from
the Update method in the Painter class. So, including updating the inputHelper object,
there are in total three instructions in the Painter.Update method:
inputHelper.Update();
gameWorld.HandleInput(inputHelper);
gameWorld.Update(gameTime);
As you can see, because the game objects themselves deal with their own behav-
ior, the task of the GameWorld object becomes very easy. The same goes for drawing
Search WWH ::




Custom Search