Button press calls method multiple times

筅森魡賤 提交于 2019-12-14 04:02:04

问题


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!


回答1:


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;
}



回答2:


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;
 }



回答3:


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;


来源:https://stackoverflow.com/questions/13259841/button-press-calls-method-multiple-times

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!