Game Development Reference
In-Depth Information
Now that the
inputHelper
object is created and updated, we can add a few convenient
methods and properties to encode some behavior and to access the data contained in
the input helper object. A very convenient method is one that checks if a particular
key has been pressed. This method returns a boolean value (
true
or
false
) indicating
whether the key has been pressed. The key that needs to be checked is passed as a
parameter. This method is given as follows:
public bool
KeyPressed(Keys k)
{
return
currentKeyboardState.IsKeyDown(k) && previousKeyboardState.IsKeyUp(k);
}
As you can see, it does not do much, except check a condition that the given key
is currently down, while it was not down in the previous state. Now that we have
this method, our
if
-instruction for checking if the player presses the R, G, or B key
becomes much simpler:
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;
A similar thing can be done for checking if the player clicked the left mouse but-
ton. We call this method
MouseLeftButtonPressed
. This method does not need any
parameters, and it also returns a value of type
bool
. The complete method is given
as follows:
public bool
MouseLeftButtonPressed()
{
return
currentMouseState.LeftButton == ButtonState.Pressed
&& previousMouseState.LeftButton == ButtonState.Released;
}
Finally, we add a property
MousePosition
that gives us a
Vector2
containing the
current mouse position. Since this is a read-only property, we only need to write a
get
part:
public
Vector2 MousePosition
{
get
{
return new
Vector2(currentMouseState.X, currentMouseState.Y); }
}
So, now we have a simple
InputHelper
class that updates the mouse and keyboard
states and that provides a few convenient methods and properties for accessing the
information. Note that this class is far from ready to be used in any complicated