多次按下按钮调用方法 [英] Button press calls method multiple times

查看:44
本文介绍了多次按下按钮调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发 XNA 游戏,但遇到了问题.每当我在游戏中按下一个键时,由按键触发的方法会被多次调用.例如,当用户按下攻击按钮(空格)时,角色在一次按键内攻击 10 次.我希望按键只触发一次该方法.即使用户按住某个键,我也希望某些方法只调用一次.现在我已经通过在每次按下按钮后编写一个 thread.sleep 来解决它,但这似乎非常低效.我希望我的问题我可以理解.提前致谢!

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!

推荐答案

您需要在按下键时将按钮标记为按下,然后在按下键时将其标记为未按下.在 keydown 方法期间.. 检查按钮是否已经按下.. 如果是.. 什么都不做,直到 keyup 将其设置回来.

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.

这样做的原因是,在按键期间,您的应用程序/游戏/任何东西每秒都会通过其消息队列接收数千条消息.即使您非常快速地按下空格键,也有可能通过消息队列处理了大约 50 条 WM_KEYDOWN 消息.

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.

示例:

bool SpacebarPressed = false;

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

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

这篇关于多次按下按钮调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆