gpt4 book ai didi

c++ - SFML 2.0 中的关键重复

转载 作者:太空狗 更新时间:2023-10-29 19:53:06 24 4
gpt4 key购买 nike

如果在 SFML 中刚刚按下(未按住)某个键,是否有一种方法可以接收,或者是否有一种方法可以模拟这种效果?

我在这里投票我的事件,

while (window.pollEvent(event));

然后在循环的后面,超出范围但发生相同的事件,我读到:

if (event.type == sf::Event::KeyPressed)
{
if (event.key.code == sf::Keyboard::Up)
{
decision--;
if (decision < 0)
decision = CHARACTER_MAX - 1;
}
}

这使得 decision 在按住向上箭头时连续递减。使用 sf::event,我可以在第一次按下时读取而不是在按住时读取吗?

此外,如果它不可能或者您不熟悉 sfml,那么用很少或没有全局化变量来模拟这种情况的最佳方法是什么? (例如 is_already_held),例如https://gamedev.stackexchange.com/questions/30826/action-button-only-true-once-per-press

我意识到这可能是唯一的方法(在更广泛的范围内声明一个变量)但我不想这样做,因为我不断地退出范围并尽可能经常地避开全局变量。

最佳答案

您可以使用 sf::Window::setKeyRepeatEnabled 禁用按键重复:

window.setKeyRepeatEnabled(false);

在创建窗口后调用它一次(足够了)。

文档是here .


如果出于任何原因您不想使用此功能,您可以使用一个 bool 值表来存储每个键的状态。这是一个伪代码,展示了如何使表保持最新并集成您的“决策”代码。

// Init the table of state. true means down, false means up.
std::array<bool, sf::Keyboard::KeyCount> keyState;
keyState.fill(true);

// :
// :

// In the event loop:
if (event.type == sf::Event::KeyPressed)
{
// If the key is UP and was not previously pressed:
if (event.key.code == sf::Keyboard::Up && !keyState[event.key.code])
{
decision--;
if (decision < 0)
decision = CHARACTER_MAX - 1;
}

// Here comes the rest of your code and at the end of the if-body:

// Update state of current key:
keyState[event.key.code] = true;
}
else if (event.type == sf::Event::KeyReleased)
{
// Update state of current key:
keyState[event.key.code] = false;
}

第三种选择是使用第三方库,例如 Thor。它仍在开发中,因此您可以期待作者的一些更改。和 here您会找到有关Action 的教程——这正是您所需要的。

关于c++ - SFML 2.0 中的关键重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17888993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com