Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to slow down or stop key presses in XNA

Tags:

I've begun writing a game using XNA Framework and have hit some simple problem I do not know how to solve correctly.

I'm displaying a menu using Texture2D and using the keyboard (or gamepad) I change the menu item that is selected. My problem is that the current function used to toggle between menu items is way too fast. I might click the down button and it will go down 5 or 6 menu items (due to the fact that Update() is called many time thus updating the selected item).

ex. (> indicate selected) > MenuItem1 MenuItem2 MenuItem3 MenuItem4 MenuItem5  I press the down key for just a second), then I have this state:  MenuItem1 MenuItem2 MenuItem3 > MenuItem4 MenuItem5  What I want is (until I press the key again) MenuItem1 > MenuItem2 MenuItem3 MenuItem4 MenuItem5 

What I am looking for is a way to either have the player click the up/down key many time in order to go from one menu item to the other, or to have some sort of minimum wait time before going to the next menu item.

like image 314
tomzx Avatar asked May 24 '09 19:05

tomzx


1 Answers

the best way to implement this is to cache the keyboard/gamepad state from the update statement that just passed.

KeyboardState oldState; ...  var newState = Keyboard.GetState();  if (newState.IsKeyDown(Keys.Down) && !oldState.IsKeyDown(Keys.Down)) {     // the player just pressed down } else if (newState.IsKeyDown(Keys.Down) && oldState.IsKeyDown(Keys.Down)) {     // the player is holding the key down } else if (!newState.IsKeyDown(Keys.Down) && oldState.IsKeyDown(Keys.Down)) {     // the player was holding the key down, but has just let it go }  oldState = newState; 

In your case, you probably only want to move "down" in the first case above, when the key was just pressed.

like image 67
Joel Martinez Avatar answered Oct 28 '22 15:10

Joel Martinez