Game Development Reference
In-Depth Information
if (currentKeyboardState.IsKeyDown(Keys.R) &&
previousKeyboardState.IsKeyUp(Keys.R))
cannon.Color = Color.Red;
else if (currentKeyboardState.IsKeyDown(Keys.G) &&
previousKeyboardState.IsKeyUp(Keys.G))
cannon.Color = Color.Green;
else if (currentKeyboardState.IsKeyDown(Keys.B) &&
previousKeyboardState.IsKeyUp(Keys.B))
cannon.Color = Color.Blue;
The same kind of thing happens for checking a mouse button press. In order
to make input handling a bit easier, we are going to create a helper class (called
InputHelper ) that will provide us with a few simple, but very useful methods and
properties. We can then use this class to make input handling in the game a lot
easier. This helper class will have two tasks:
1. maintain the previous and current mouse and keyboard states, and
2. provide methods and properties that allow for easy access of mouse and keyboard
information.
Once we have written this helper class, we can make an instance of it in our game
and use it in our HandleInput method. The InputHelper class needs to store the current
and previous keyboard and mouse state, so we at least need the following member
variables:
MouseState currentMouseState, previousMouseState;
KeyboardState currentKeyboardState, previousKeyboardState;
Also, these states need to be updated at the beginning of every update. We therefore
add an Update method to this class that copies the last 'current' mouse and keyboard
state to the previous state and that retrieves the current state:
public void Update()
{
previousMouseState = currentMouseState;
previousKeyboardState = currentKeyboardState;
currentMouseState = Mouse.GetState();
currentKeyboardState = Keyboard.GetState();
}
In the Painter class, we create an instance of the InputHelper class in the constructor
that we store as a member variable:
inputHelper = new InputHelper();
This inputHelper object is updated in the first instruction of the Update method of the
Painter class:
inputHelper.Update();
Search WWH ::




Custom Search