检测是否按下了按键,而不是按下按键

时间:2018-01-17 20:51:25

标签: c++ input keyboard mouse sfml

我是SFML的新手,我无法找到解决方案来检查是否在一帧期间按下某个键。我遇到的问题是,使用KeyboardMouse类,似乎不可能使用一个系统,其中首先在任何{{1}之前检查当前输入状态调用对象,然后在Update()之后,您获得下一帧的先前输入状态,以便可以执行以下操作:

Update()

但这似乎不适用于SFML,其他来源告诉我,我假设 bool Entity::KeyboardCheckPressed(sf::Keyboard::Key aKey) { //this part doesn't work if (KeyboardState->isKeyPressed(aKey) and !PreviousKeyboardState->isKeyPressed(aKey)) { return true; } return false; } 类使用Eventtype如下例所示:

key.code

但是这会导致bool Entity::KeyboardCheckPressed(sf::Keyboard::Key aKey) { if (Event->type == sf::Event::KeyPressed) { if (Event->key.code == aKey) { return true; } } return false; } sf::Event::KeyPressed做同样的事情,所以我尝试了将密钥重复设置为false的方法:KeyboardState->isKeyPressed(aKey)没有任何结果。我还发现window.setKeyRepeatEnabled(false);只能在main.cpp中的这个部分内部工作:

sf::Event::KeyPressed

这个问题是我想处理我的Entity对象里面的Input' while (window.pollEvent(event)) { } 函数,我无法将整个Update循环放在Update()内。所以我在这里,努力寻找解决方案。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

一般情况下,如果你有一个可以检查当前状态的东西,并且你想检查帧之间是否有状态改变,你只需使用在应用程序循环外声明的变量来存储先前的状态,并将其与当前状态进行比较。

bool previousState = checkState();
while (true) {
    // your main application loop

    bool newState = checkState();
    if (newState == true && previousState == false) {
        doThingy("the thing went from false to true");
    } else if (newState == false && previousState == true) {
        doThingy("the thing went from true to false");
    } else {
        doThingy("no change in the thing");
    }

    // this is done unconditionally every frame
    previousState = newState;
}