Saturday, November 17, 2007

How can I check if a key is down or not?

Question: How can I check if a key is down or not?

Answer: To check the state of a key on the keyboard, can call the IsKeyDown or IsKeyUp methods of a KeyboardState variable.

Inside of the Update method, create a KeyboardState and set it to the current state of the Keyboard.

KeyboardState keyboard = Keyboard.GetState();

After that, you can add the if-statement to check the value of a given key:

if (keyboard.IsKeyDown(Keys.Space))
{
//Code
}


By using the Keys enum type, we can check against any key on the keyboard.

No comments: