检测是否按下了某个键,而不是检测它是否始终处于关闭状态
Detecting if a key was pressed, not if it is always down
我是SFML的新手,我很难找到检查在一帧中是否按下了键的解决方案。我一直面临的问题是,对于Keyboard
和Mouse
类,似乎不可能使用一个系统,在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
类及其type
和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
做与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;
}
相关文章:
- 如何检测是否在缓冲绘画动画中绘制最后一帧?
- 检测是否存在具有 C++17 的类成员
- 如何检测是否例如.T::is_transparent 是定义的?
- 检测是否存在具有给定签名的函数
- 检测是否在 QTableWidget 中添加或删除了列
- Qt安装程序框架:检测是否安装了VC++可再发行组件
- SFINAE 检测是否定义了类型
- 检测是否按住 SHIFT
- 如何检测是否未使用 c++ 分析整个字符串
- 有没有办法在编译时检测是否可以使用一组给定的参数类型成功调用通用 lambda?
- 检测是否正在执行捕获块
- 检测是否按下了某个键,而不是检测它是否始终处于关闭状态
- 检测是否安装了Office 365
- 如何检测是否有任何应用程序进入全屏或退出全屏?
- 检测是否从 USB 驱动器运行
- C 检测是否存在接受特定类型的函数
- 在编译时检测是否存在默认构造函数
- 检测是否已从注入的 dll 调用函数
- 使用OpenCV教程中的任何一个进行人脸检测是否有任何函数可以计算绘制在人脸上的矩形的大小
- 是否有某种方法可以检测是否使用非虚拟基析构函数错误地删除了类