c++ - SFML 形状无限旋转

标签 c++ events keyboard sfml shapes

我正在制作一个围绕图形移动的机器人 ARM ,但是当我尝试使用键盘旋转一个形状时,它会无限旋转:我希望它在我按下右箭头时只旋转一次。我该如何解决这个问题?

Transform transform;    
while (window.isOpen())
{
    Event event;
    while (window.pollEvent(event))
    {
        if (event.type == Event::Closed)
            window.close();

    }
    if (event.type == Event::KeyPressed)
    {
        switch (event.key.code)
        {
        case Keyboard::Right:
            ang += 1;
        }
    }

    window.clear(Color::White);
    window.draw(braccio, transform);
    transform.rotate(ang, WIDTH / 2, HEIGHT / 2);
    window.draw(assi);
    window.display();
}

最佳答案

现在,这条线

transform.rotate(ang, WIDTH / 2, HEIGHT / 2);

在程序的每一帧调用,因为它在主循环中,不断运行。如果您希望它仅在您的游戏检测到某些输入时发生,请将其放入您的事件轮询中,如下所示:

while (window.pollEvent(event))
{
    // Do your event handling in here, input, etc.

    if (event.type == Event::Closed)
        window.close();

    // This event case should also be inside here.
    if (event.type == Event::KeyPressed)
    {
        switch (event.key.code)
        {
            case Keyboard::Right:
                transform.rotate(ang, WIDTH / 2, HEIGHT / 2); 
                break;
        }
    }
}

否则你的 ARM 将无限期地继续旋转。

编辑:感谢@alseether 指出 Transform::rotate 函数将角度添加到形状的当前旋转。所以每次增加 ang 会逐渐使形状旋转得越来越快......如果你不想发生这种情况,只需将 ang 设置为一个常量值,它就会以恒定速率旋转立方体。

关于c++ - SFML 形状无限旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58418179/

相关文章:

ios - 在自定义键盘上需要帮助

安卓悬浮键盘

c++ - 将类类型传递给 Windows 窗体构造函数并必须将其转换为类指针才能使用它

c++ - 如何有效地将 std::vector<char> 复制到 std::string

c# - 事件与事件处理程序

ios - 如何从 UITableViewCell 中的 Switch 捕获事件?

JQuery - 将点击事件添加到 LI 或 SPAN 元素?

c++ - Bison/Flex Concat 字符 *

c++ - SteamVR 覆盖 Controller 输入?

android - 从另一个 Activity 返回时,SearchView 获得焦点并打开键盘