Our 2D games will need to check if the player is clicking on something at some point. Clicking means that the player has both pressed and released a button. How can you check for both of these binary (one or the other) conditions at once?
The answer lies in two different states being monitored for the input device. And today we will discuss how to detect a ‘click’ with a 360 GamePad. This can easily be translated to a keyboard as well, but I’ll leave that up to you and the MSDN XNA Game Studio 3.0 Library to figure out.
This code will declare a global variable to hold the previous and current state of a GamePad. This includes the thumb stick orientation, which buttons are pressed, etc. I chose to use a global variable so that all of my classes can access the current state at any given time.
Initializing the GamePad in the Game.cs class member declarations:
public static GamePadState previousGamePadState =
GamePad.GetState(PlayerIndex.One);
public static GamePadState gamePadState =
GamePad.GetState(PlayerIndex.One);
At the end of the Update(); function in Game.cs and before base.Update(gameTime); is called, add the following:
previousGamePadState = gamePadState;
Now you are able to keep track of both the current state of a GamePad and the one from the last time Update(); was called [Update(); is called at 60fps unless you have specified it to run otherwise]from within any class.
The next article will describe one way to implement this code to respond to user clicks at any given moment. There are some libraries that can make this easier for you, but before you throw off calculations to code someone else wrote, it would be best to fully understand it yourself.
No comments:
Post a Comment