SFML 2.0中的重复重复

Jam*_*ley 3 c++ keyboard events sfml

如果刚刚在SFML中按下(未保持)某个键,或者是模仿这种效果的方法,有没有办法接收?

我在这里调查我的活动,

while (window.pollEvent(event));
Run Code Online (Sandbox Code Playgroud)

然后在循环中,超出范围,但同样的事件,我读到:

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

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

另外,如果它不可能或你不熟悉sfml,那么用很少或没有全局变量来模仿这样的最好的方法是什么?(例如is_already_held),例如https://gamedev.stackexchange.com/questions/30826/action-button-only-true-once-per-press

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

Hiu*_*ura 7

您可以使用以下命令禁用密钥重复sf::Window::setKeyRepeatEnabled:

window.setKeyRepeatEnabled(false);
Run Code Online (Sandbox Code Playgroud)

创建窗口后调用一次(这就够了).

文档在这里.


如果出于任何原因,您不想使用此函数,则可以使用布尔表来存储每个键的状态.这是一个伪代码,显示如何使表保持最新并集成您的"决策"代码.

// 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;
}
Run Code Online (Sandbox Code Playgroud)

第三种方法是使用Thor等第三方库.它仍在开发中,因此您可以期待作者的一些更改.而在这里,你会发现在一个教程行动 -也就是你所需要的东西.