Skip to main content
gamedev.net
🔒 Locked

[.net] XNA Keypress problem

Started by coolblue Dec 27, 2006 at 2:56 PM 5 replies 3.3k views
Original Post
coolblue
coolblue
I am using the following to retrieve a keypress:- if (newState.IsKeyDown(Keys.Space)) { // code } The spacebar is used to fire bullets in my 2d game but if I press it once very quickly it registers as 3 keypresses. Is there an easy way to make it a bit less sensitive?
templewulf
templewulf
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 up state 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.
XBox 360 gamertag: templewulf feel free to add me!
LostLogic
LostLogic
I've used timers in the past to get around this. For example, I put a timer value on each key that contains the last time the key was pressed and only allow updates if a certain amount of time has passed.
LostLogicwww.GamerOutfit.comXBox 360 Community Games Reviews and NewsExisled - 2D/3D Shooter for XBox 360
ChurchSkiz
ChurchSkiz
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.
coolblue
coolblue
Thanks for the help.

I have now sorted this using keystates.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.