XNA supplies us with a KeyboardState, that we can use to check whether a certain key has been pressed. But, it doesn’t check if that key is being held down. This can be a problem in some cases… For example, say we want to open a menu when the user presses the ‘escape’ key. If we just did the usual check of myKeyboardState.IsKeyDown(Keys.Escape) it would return true every iteration of your update function. This, would cause the menu to flash on/off multiple times and it gets annoying… fast. So, to fix this, create 2 private (or public) variables:
private KeyboardState keyboardState;
private KeyboardState lastKeyboardState;
In either your LoadContent() or Initialize() set
lastKeyboardState = Keyboard.GetState();
And at the top of your Update() function add
lastKeyboardState = keyboardState;
keyboardState = Keyboard.GetState();
Then, using a simple function
private bool HasKeyBeenPressed(Keys key)
{
if(keyboardState.IsKeyDown(key) && lastKeyboardState.IsKeyUp(key)
{
return true;
}
else
{
return false;
}
}
you can now check whether a key has been pressed, instead of just being held down! You can call it like so HasKeyBeenPressed(Keys.Escape);
Hope this helps!