【问题标题】:Detecting if a key was pressed, not if it is always down检测一个键是否被按下,而不是它是否总是按下
【发布时间】:2018-06-26 20:18:31
【问题描述】:

我是 SFML 的新手,我很难找到一个解决方案来检查是否在一帧中按下了某个键。我一直面临的问题是,对于KeyboardMouse 类,似乎不可能使用这样一个系统,即在任何Update() 对象调用之前首先检查当前输入状态,然后毕竟Update() 您获得下一帧的先前输入状态,以便可以执行以下操作:

    bool Entity::KeyboardCheckPressed(sf::Keyboard::Key aKey)
    {
        //this part doesn't work 
        if (KeyboardState->isKeyPressed(aKey) and !PreviousKeyboardState->isKeyPressed(aKey))
        {
            return true;
        }
        return false;
    }

但这似乎不适用于 SFML,其他消息来源告诉我,我想使用 Event 类及其 typekey.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::KeyPressedKeyboardState->isKeyPressed(aKey) 执行相同的操作,因此我尝试了将键重复设置为false 的方法:window.setKeyRepeatEnabled(false); 没有任何结果。我还发现sf::Event::KeyPressed 仅在 main.cpp 中的此部分内部按预期工作:

while (window.pollEvent(event))
{

}

问题在于我想在我的实体对象的Update()function 中处理 Input,而我不能将整个 Update 循环放在 while (window.pollEvent(event)) 中。所以我在这里,努力寻找解决方案。任何帮助表示赞赏。

【问题讨论】:

  • 为什么你想在你的实体Update()函数中处理输入?
  • @NaCl 也许我没有正确表达自己,我的意思是我只能说 if(KeyboardCheckPressed(sf::Keyboard::aKey))//do something, inside of any继承自 Entity 基类的对象。
  • 编写一个包含一堆布尔值的包装类,这些布尔值会在您希望它们更新时准确更新

标签: c++ input keyboard mouse sfml


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 2022-10-14
    • 2021-07-14
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多