Original Post
🔒 Locked
[.net] XNA Keypress problem
Advertisement
As an expansion on what the AP said:
It registers a press for each update that the spacebar is held down. Unless you can press and release the spacebar faster than one iteration of your update loop, it's going to register more than once.
What you need to implement is states for buttons. Each key that is a control in your game has a downstate and an up state. What you want to capture is the event of going from up to down. So, there are four events you need to model with those two states for each key: going down, staying down, going up and staying up. Many developers ignore the staying upstate event, assuming that up is the natural state for every key (which is what I do). You may or may not need to implement the staying down state event, especially if you have "charging" effects, like Mega Man's Megabuster.
It registers a press for each update that the spacebar is held down. Unless you can press and release the spacebar faster than one iteration of your update loop, it's going to register more than once.
What you need to implement is states for buttons. Each key that is a control in your game has a downstate and an up state. What you want to capture is the event of going from up to down. So, there are four events you need to model with those two states for each key: going down, staying down, going up and staying up. Many developers ignore the staying up
In DirectX I would have done what temple said, but if you read the XNA help files they standardize the method (you can read about it in the help files). Basically you create two keyboard states, old and new. When you want to test for a key press (not down) you would do this...
if(newstate.iskeydown(keys.space) && !oldstate.iskeydown(keys.space) )
//perform action
you set the new keystate to the current keystate at the beginning of the update loop, and set the old keystate to the new keystate at the end of the update loop. This will fire only once per key press.
if(newstate.iskeydown(keys.space) && !oldstate.iskeydown(keys.space) )
//perform action
you set the new keystate to the current keystate at the beginning of the update loop, and set the old keystate to the new keystate at the end of the update loop. This will fire only once per key press.
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement