Game Creation with XNA/Basics/Input Devices

From Wikibooks, open books for an open world
Jump to: navigation, search

Input Devices[edit]


Input Devices is one of the most important chapters in a handbook for game creation. A computer (or Xbox) game subsists on interaction with the user - that is why there needs be to a method to check the user input and to let game react on this input.

XNA makes it very easy to control the user devices. It offers an easy-to-use and understandable API for access to mouse, keyboard and gamepad. Using this it is possible to write an user-interaction scheme in a short time. Basically XNA offers easy access to:

  • Mouse
  • Keyboard
  • Gamepad

The basic concept is the same for all controller types. XNA provides a set of static classes (one for each type) which can be used to retrieve the status and all properties (e.g. pressed buttons, movements, ...) of the input device.

This detection is usually located in the Update()-method of the game loop to retrieve the status as often as possible. Storing the states of all input devices in class variables allow it to check the status in other methods and classes. It is a common solution to have an array of boolean variables in the class which represent the status of all controllers - namely the pressed buttons on the controller, the mouse movements and clicks and the pressed keys on the keyboard.

protected override void Update(GameTime gameTime)
    KeyboardState kbState = Keyboard.GetState();
    // ...

Windows vs. Xbox[edit]

Windows and Xbox games are usually played in a different way. In general a Windows computer is controlled by a mouse and a keyboard, whereas an Xbox is often controlled by a gamepad. Therefore it needs a control structure to decide whether the code is executed on Windows or Xbox to set a default controller for the game.

#if XBOX
// this code is embedded only in xbox project

But it is also possible to connect a mouse or keyboard to an Xbox as well as to connect an Xbox controller to a Windows computer. So in most of the cases it is better to check for example if a gamepad is connected. Another way of dealing with that problem is to store the user's controller of choice in a variable. So the user may decide which controller he likes to use to play your game.


Wireless Mouse

At first you have to get an instance of the mouse state by calling the static GetState()-method of the Mouse class. This object now gives you access to a lot of public attributes from the connected mouse.

MouseState mouse = Mouse.GetState();
bool leftButton = (mouse.LeftButton == ButtonState.Pressed); // left mouse button
bool middleButton = (mouse.MiddleButton == ButtonState.Pressed); // middle mouse button
bool rightButton = (mouse.RightButton == ButtonState.Pressed); // right mouse button
int x = mouse.X; // horizontal mouse position
int y = mouse.Y; // vertical mouse position
int scroll = mouse.ScrollWheelValue; // scroll wheel value

The state of the mouse buttons is read through the attribute "xxxButton" (where xxx stands for the type - left, middle, right). If you compare this value with ButtonState.Pressed or ButtonState.Released you can retrieve the state of this button. In the example above it stores the state of each button in a boolean variable that is true if the associated button is pressed.

The mouse position on the screen is stored in the X and Y attribute of the mouse object. This value is always positive (as it starts with 0,0 in left upper corner) and may be compared to further mouse positions (in a game logic) to detect a specific movement of the mouse. A simple example would be:

MouseState mouse = Mouse.GetState();
int x = mouse.X;
int y = mouse.Y;
deltaX = oldX - x; // difference of horizontal positions
deltaY = oldY - y; // difference of vertical positions
oldX = x;
oldY = y;

Most of the modern mouse also have a scroll wheel that is often used in games, for example to zoom, to scroll or to switch between different weapons. The attribute ScrollWheelValue is an integer that represents the scroll state of the mouse.

To recognize the movement of the scroll wheel it is necessary to store some older values and compare them with each other. The sign of this difference indicates the scroll direction and the absolute value indicates the speed of scroll movement.


Cherry Keyboard

To check the state of the keys on a keyboard is very simple. At first you have to get an KeyboardState object by calling the static method GetState from the Keyboard class. This instance now lets you retrieve the state of specific keys.

KeyboardState keyboard = Keyboard.GetState();
bool keyB = keyboard.IsKeyDown(Keys.B); // key "B" on keyboard
bool keyArrowLeft = keyboard.IsKeyDown(Keys.Left); // arrow left on keyboard

The boolean variables keyB and keyArrowLeft now store "true" if the specific key is pressed right now or "false" if it is not pressed. This method can be repeated for each key that is of interest for the application or game.

It is also possible to directly get an array of all keys of the keyboard that are currently pressed. A call of the method GetPressedKeys returns an array of Keys that can be traversed key by key.

KeyboardState keyboard = Keyboard.GetState();
Keys[] keys = keyboard.GetPressedKeys(); // array of keys


The gamepad is the most convenient way to play a game on the Xbox. Despite XNA is designed to develop games for Windows as well as for Xbox, the default API only supports the original Xbox controller. Based on that fact you have to decide whether you want to force your user to use (and maybe buy) the Xbox gamepad or if you want to support any other gamepads for example from Logitech.

That might be more comfortable for the user, though it means more coding effort for the developer. In this chapter I want to describe the implementation for both the Xbox controller and all other controllers.

Xbox Gamepad[edit]

Xbox 360 Wireless Controller

Accessing this input device is nearly as easy as checking the state of mouse or keyboard. One (and important) difference is that XNA makes it able to connect up to four different gamepads to the Xbox or Windows computer.

So it is (often) necessary to implement a loop over all gamepads that are connected to check their states individually. How this (and more) can be done is explained in the following paragraphs.

GamePadState[] gamePad = new GamePadState[4];
for(int i = 0; i < 4; i++) { // loop over up to 4 gamepads
    gamePad[i] = GamePad.GetState(i); // get state of gamepad
    if(gamePad[i].IsConnected) {
        // gamepad is connected

In this loop you can access all attributes like the buttons (front and shoulder), the digital pad and the two analog sticks. Here is how you do it:

bool aButton = (gamePad[0].Buttons.A == ButtonState.Pressed); // button A
bool leftDigital = (gamePad[0].DPad.Right == ButtonState.Pressed); // left button on digital pad
int leftStick = gamePad[0].ThumbSticks.Left.X; // horizontal position of left stick

The rumble effect lets the gamepad vibrate and gives the player a special feedback to his actions in the game. For instance a hit by an opponent in a shooter game or a crash in a racing game could cause such feedback. The second and third parameter control the intensity of the rumbling effect.

GamePad.SetVibration(int controllerNr, float leftRumble, float rightRumble); // make the controller rumble

Other Gamepads[edit]

Microsoft Sidewinder Gamepad

Other gamepads than the original Xbox controller are not supported by XNA. But it is possible to integrate a support for them with a free library which is called SlimDX.

In addition you need a helper class that can be found here - it uses SlimDX to check the gamepad state of controllers that are not the original Xbox controller.

If you have downloaded, installed and integrated both the SlimDX library and the helper class you can use the following code to check the gamepad states - like you have done with the Xbox controller in XNA.

controller = new GameController(this, 0); // number of gamepad
GameControllerState state = controller.GetState();
bool button1 = state.GetButtons()[1]; // button 1 pressed


Xbox 360 Kinect Standalone

Kinect is a revolutionary video camera for the Xbox that recognizes your movement in front of the television. This can be used to control games just with your body. Developers can use the Kinect framework to integrate this into their game.