检测是否按下了某个键,而不是检测它是否始终处于关闭状态

Detecting if a key was pressed, not if it is always down

本文关键字:检测 是否 状态 于关闭      更新时间:2023-10-16

我是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::KeyPressed做与KeyboardState->isKeyPressed(aKey)相同的操作,因此我尝试了将键重复设置为 false 的方法:window.setKeyRepeatEnabled(false);没有任何结果。我还发现sf::Event::KeyPressed仅在主部分的这部分内按预期工作.cpp:

while (window.pollEvent(event))
{
}

这样做的问题是我想在我的实体对象的Update()函数中处理输入,并且我无法将整个更新循环放在while (window.pollEvent(event))内。所以我在这里,努力寻找解决方案。任何帮助,不胜感激。

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

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