Wednesday, October 18, 2017

xna - How can I stop looking for keyboard input for a length of time?


I'm pretty new to programming, and even newer to C# and XNA. I currently call a method that looks for keyboard input in my Update method. This method has if statements for doing what needs to be done when a key has been pressed. The problem is, since it's being called constantly, it's impossible to press a key quickly enough for it to register only once.


One issue this creates is going through a menu. A short tap of a key sends the "cursor" that indicates which menu item is selected wheeling through the menu several times. I'd like to be able to "turn off" keyboard input for perhaps a fourth of a second after any valid key has been pressed.



Answer



What you're trying to do is simple to solve without having to resort to doing any timing on the input (in fact I recommend you not to do so in this case - timing is more useful for scenarios such as limiting the firing rate of a spaceship).


If you want for only the initial press of the key to be registered, the way it's usually done is:



  1. Keep track of both the current and the previous frame's keyboard state.


  2. Detect a key press by checking if the key is down in the current frame but was up on the previous frame.


Code example:


private KeyboardState _currentKeyboardState;
private KeyboardState _previousKeyboardState;

public void Update(GameTime elapsed)
{
// Before handling input
_currentKeyboardState = Keyboard.GetState();


if(_currentKeyboardState.IsKeyDown(Keys.Down) &&
_previousKeyboardState.IsKeyUp(Keys.Down))
{
// Handle key press of the down key
}

//

// After handling input

_previousKeyboardState = _currentKeyboardState;
}

Personally, I like to wrap this up in some separate InputManager class and provide methods such as IsKeyDown(key) versus OnKeyPress(key) to distinguish both scenarios clearly.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...