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!
Share
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: