C++ SFML - 如何读取同时按下的 SFML 中的两个键?
C++ SFML - How to read two keys in SFML pressed at the same time?
我做了一个很简单的双人游戏,一个是水母,一个是SFML中的鲨鱼。唯一的问题是一次只能有一个精灵移动。这可以修复吗?我该如何修复?
编辑:我的尝试是这样的:
if (event.type == sf::Event::KeyPressed)
{
bool D;
bool A;
bool S;
bool W;
bool Up;
bool Right;
bool Left;
bool Down;
if (event.key.code == sf::Keyboard::A)
A = true;
if (event.key.code == sf::Keyboard::D)
D = true;
if (event.key.code == sf::Keyboard::W)
W = true;
if (event.key.code == sf::Keyboard::S)
S = true;
if (event.key.code == sf::Keyboard::Left)
Left = true;
if (event.key.code == sf::Keyboard::Right)
Right = true;
if (event.key.code == sf::Keyboard::Up)
Up = true;
if (event.key.code == sf::Keyboard::Down)
Down = true;
if (D and Right)
{
jelly.move(10, 0)
}
...
}
您可以通过设置一个标志来解决它,该标志在按下一个键时设置,并在释放该键时清除。然后你可以在按下另一个键时检查这个标志。
或者,您可以使用 sf::Keyboard::isKeyPressed
探测键盘在给定点的状态。
您当前代码的一个问题是所有变量都是 if 语句的局部变量,因此在处理下一个事件时会重新初始化。它们应该在 if
之外定义。另一个问题是您没有处理 KeyReleased
事件。
我做了一个很简单的双人游戏,一个是水母,一个是SFML中的鲨鱼。唯一的问题是一次只能有一个精灵移动。这可以修复吗?我该如何修复?
编辑:我的尝试是这样的:
if (event.type == sf::Event::KeyPressed)
{
bool D;
bool A;
bool S;
bool W;
bool Up;
bool Right;
bool Left;
bool Down;
if (event.key.code == sf::Keyboard::A)
A = true;
if (event.key.code == sf::Keyboard::D)
D = true;
if (event.key.code == sf::Keyboard::W)
W = true;
if (event.key.code == sf::Keyboard::S)
S = true;
if (event.key.code == sf::Keyboard::Left)
Left = true;
if (event.key.code == sf::Keyboard::Right)
Right = true;
if (event.key.code == sf::Keyboard::Up)
Up = true;
if (event.key.code == sf::Keyboard::Down)
Down = true;
if (D and Right)
{
jelly.move(10, 0)
}
...
}
您可以通过设置一个标志来解决它,该标志在按下一个键时设置,并在释放该键时清除。然后你可以在按下另一个键时检查这个标志。
或者,您可以使用 sf::Keyboard::isKeyPressed
探测键盘在给定点的状态。
您当前代码的一个问题是所有变量都是 if 语句的局部变量,因此在处理下一个事件时会重新初始化。它们应该在 if
之外定义。另一个问题是您没有处理 KeyReleased
事件。