I am hoping that the next tutorial will be ready Sunday. But until then I want to make a mini-post.
I find the documentation on how to check if a key has been pressed and released a little confusing. Here is a simple way to do it. You need to save the old state of the keyboard and compare it to the current state of the keyboard. I believe what they are checking is if the current state of the keyboard the key is down and the last state of the keyboard is up. I think that it works better if the current state of the keyboard is up and the last state of the keyboard is down.
So, create an XNA game. In the Game1.cs file add a variable at the top of the class to hold the old state of the keyboard and a variable to hold a color:
KeyboardState oldState;
Color bgColor = Color.White;
Now in the Update method add a call to a new method:
CheckKeyboard();
Now, write the CheckKeyboard method as follows:
private void CheckKeyboard()
{
KeyboardState currentState = Keyboard.GetState();
if (currentState.IsKeyUp(Keys.Space))
{
if (oldState.IsKeyDown(Keys.Space))
{
bgColor = new Color((byte)~bgColor.R,
(byte)~bgColor.G,
(byte)~bgColor.B);
}
}
oldState = currentState;
}
Now just replace the Color.CornflowerBlue in the Clear call to bgColor in the Draw method. When you run the program the screen should switch between black and white when you press the Space key and let it go.
Give it a try and see how it works. I am not posting the project for this simple tutorial.
Friday, April 3, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment