Would you like my Input?

A basic input wrapper for your XNA games. This sample demonstrates a simple way of defining and collecting inputs for your games.

Would you like my Input?

Defining and collecting keyboard/gamepad input for your XNA Games

A game is not much of a game if you don’t have any way of gathering input. With the XNA framework, you typically are querying input coming in from the keyboard and the Xbox 360 gamepad. Your code then often begins to look like this.

            GamePadState CurrentGamePadState = GamePad.GetState(PlayerIndex.One);
            KeyboardState CurrentKeyboardState = Keyboard.GetState();
            if ((CurrentGamePadState.Buttons.A == ButtonState.Pressed && PreviousGamePadState.Buttons.A == ButtonState.Released)
                || (CurrentKeyboardState.IsKeyDown(Keys.A) && PreviousKeyboardState.IsKeyDown(Keys.A) == false))
                //Then Jump!
            PreviousGamePadState = CurrentGamePadState;
            PreviousKeyboardState = CurrentKeyboardState;


And the more inputs you’re looking for the nastier that begins to look. This is where an Input Wrapper becomes very useful. The one I’ve written allows you to define an action such as “Jump” and then define just what inputs makeup a “Jump”.

Below is an example of assigning inputs to a “Jump” action.

            //Add keyboard and gamepad inputs for Jump
            mGameInput.AddGamePadInput(“Jump”, Buttons.A, true);
            mGameInput.AddKeyboardInput(“Jump”, Keys.A, true);
            mGameInput.AddKeyboardInput(“Jump”, Keys.Space, false);


So the above code is adding one gamepad input and two keyboard inputs for the action “Jump”. The third parameter indicates whether the user has to have released the input previously for it to be considered an input. So if they hold the “A” button down, does the character keep jumping or do they have to press it and release each time.

Now, to check for an input all we have to do is the following in the Update() method.

            if (mGameInput.IsPressed("Jump", PlayerIndex.One))


That one single line of code will now correctly tell you if the A button on the gamepad is being pressed (and was previously released) or if the A key on the keyboard is being pressed (and was previously released) or if the Spacebar on the keyboard is being pressed. Much simpler right?

I’ve provided the source code for you to enhance or use as is. The source code has an example in the Game1.cs class of setting up the Input wrapper and then using it. And I always tried to be fairly liberal with the comments in the code.  I’ve been using this in my games and so far it’s been working out fairly well and hopefully it’s of benefit to the XNA community as well.

As always, feel free to leave me any feedback or comments. I love hearing from the community!

Technorati Tags: