user1621127
user1621127

Reputation: 301

Button press calls method multiple times

i'm working on a XNA game and i've encountered a problem. Whenever i press a key in the game, the method that is triggered by the key press is called multiple times. For example, when the user presses the attack button (space) the character attacks like 10 times within one key press. I want the key press to trigger the method just one time. Even if the user holds down a key i want some methods to be called only once. For now i've solved it by writing a thread.sleep after each button press, but that seems VERY unefficient. I hope my problem i understandable. Thanks in advance!

Upvotes: 1

Views: 1780

Answers (3)

Cyral
Cyral

Reputation: 14163

I know this has been answered, But you can use a method like this. Having oldKeyBoardState one frame behind the current one, and doingIsKeyToggled(Keys.Space)

bool IsKeyToggled(Keys key)
{
    if (!oldKeyBoardState.IsKeyDown(key) && keyboardState.IsKeyDown(key))
       return true;
    else
       return false;
}

Use to set one behind, you will need 2 global variables.

 public static KeyboardState keyboardState;
 public static KeyboardState oldKeyBoardState;

Your Update() method should look like this:

 protected override void Update(GameTime gameTime)
 {
   keyboardState = Keyboard.GetState();
   //TODO: Add update logic here
   //This comes last
   oldKeyBoardState = keyboardState;
 }

Upvotes: 2

Austin Henley
Austin Henley

Reputation: 4633

You need a flag that you set when the key is first pressed and then reset when the key is released. A rough example:

if(keyIsPressed() && !myFlag)
{
   //do stuff
   myFlag = true;
}
else if(!keyIsPressed())
   myFlag = false;

Upvotes: 0

Simon Whitehead
Simon Whitehead

Reputation: 65097

You need to flag the button as pressed on keydown, then flag it unpressed on keyup. During the keydown method.. check if the button is already down.. if it is.. do nothing until keyup sets it back.

The reason for this is, during a key press, your application/game/whatever is receiving thousands of messages per second through its message queue. Even if you smack the spacebar super quickly, chances are ~50 WM_KEYDOWN messages were processed through the message queue.

Example:

bool SpacebarPressed = false;

private void KeyDown() {
    if (!SpacebarPressed) {
        SpacebarPressed = true;
        DoSomethingWithSpacebarBeingPressed();
    }
}

private void KeyUp() {
    if (SpacebarPressed) SpacebarPressed = false;
}

Upvotes: 5

Related Questions