Game Development Reference
In-Depth Information
if
(calculateAngle)
{
−
double
opposite = currentMouseState.Y
barrelPosition.Y;
−
barrelPosition.X;
angle = (
float
)Math.Atan2(opposite, adjacent);
double
adjacent = currentMouseState.X
}
else
angle = 0.0f;
6.5 Handling Keyboard and Gamepad Input
6.5.1 Basics of Handling Keyboard Input
Handling keyboard and gamepad input is dealt with in a very similar way to dealing
with mouse input. Instead of getting the mouse state, we have to get the
keyboard
or
gamepad
state. This can be done as follows:
KeyboardState currentKBState = Keyboard.GetState();
GamePadState currentGPState = GamePad.GetState();
Also, just like the mouse state, these variables have several methods for checking
if the player presses a key on the keyboard, or a button on the gamepad. For ex-
ample, we can check if the player presses the 'A' button on the gamepad by call-
ing
currentGPState.IsButtonDown(Buttons.A)
. Similarly, we check if the 'A' key on the
keyboard is pressed by calling
currentKBState.IsKeyDown(Keys.A)
. The classes
Buttons
and
Keys
provide a number of properties for defining the available keys and but-
tons.
6.5.2 A Multicolored Cannon
The program
Painter2
is an extension of the
Painter1
program. It also features a rotat-
ing cannon, but now the player can also select the color of the cannon by pressing
different keys (R, G, or B). The current color of the cannon is displayed on the
screen by drawing a colored ball in the center of the rotating barrel. The cannon can
be either red, green, or blue. So, we will need three images of a ball, one for each of
the three colors:
Texture2D colorRed, colorGreen, colorBlue;
To make things a bit more convenient, we will declare an extra
Texture2
variable
called
currentColor
, in which we keep track of what the current color of the cannon
is: