【问题标题】:Moving a sprite and handling events移动精灵和处理事件
【发布时间】:2011-11-24 19:02:56
【问题描述】:

我目前正在学习 SFML 库,但我对移动精灵有点迷茫。这是我的 main.cpp 文件:

#include <SFML/Graphics.hpp>

int main()
{
    // Create the main window
    sf::RenderWindow App(sf::VideoMode(800, 600), "SFML window");

    // Load a sprite to display
    sf::Texture Image;
    if (!Image.LoadFromFile("cb.bmp"))
        return EXIT_FAILURE;
    sf::Sprite Sprite(Image);

    // Define the spead of the sprite
    float spriteSpeed = 10.f;

    // Start the game loop
    while (App.IsOpened())
    {
        // Process events
        sf::Event Event;
        while (App.PollEvent(Event))
        {
            // Close window : exit
            if (Event.Type == sf::Event::Closed)
                App.Close();
            if (sf::Keyboard::IsKeyPressed(sf::Keyboard::Up))
                Sprite.Move(spriteSpeed * App.GetFrameTime(), 0);
        }

        // Clear screen
        App.Clear();

        // Draw the sprite
        App.Draw(Sprite);

        // Update the window
        App.Display();
    }

    return EXIT_SUCCESS;
}

但是我的动作真的很慢,动作不一致,为什么精灵不能在屏幕上稳定地移动?另外,看看我打算如何使用鼠标来控制角色,我将如何使用循环使角色向用户单击的位置移动?

【问题讨论】:

  • 如果玩家立即跟随鼠标,则将其位置设置为鼠标所在的位置而不移动他,否则,您将计算位移的方向,并将其乘以速度和使用移动功能。

标签: c++ sfml


【解决方案1】:

您不应该在事件循环中检查键是否被按住。

SFML 仅在第一次按下按键时发布一个事件,然后在松开按键时发布另一个事件。在这种情况下,您的代码仅在发生事件(例如移动鼠标、单击或其他任何事情)时检查是否保持键。

IsKeyPressed 移出事件循环,最好在它下方,应该可以解决问题。

让精灵向鼠标移动是一个更复杂的问题,更适合Game Development StackExchange

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多