【问题标题】:Make Object Move Smoothly In C++-SFML在 C++-SFML 中使对象平滑移动
【发布时间】:2015-04-18 16:50:08
【问题描述】:

嘿,伙计们,我是使用 C++ 和 Sfml 进行游戏开发的初学者,我编写了这段代码来使紫色对象移动,但问题是它移动不顺畅,就像文本输入一样,如何解决这个问题?

这是我的代码:

#include <SFML/Graphics.hpp>

int main()
{
    sf::ContextSettings settings;
    settings.antialiasingLevel = 12;

    sf::RenderWindow window(sf::VideoMode(640, 480), "Ala Eddine", sf::Style::Default, settings);

    sf::CircleShape player(20, 5);
    player.setFillColor(sf::Color(150, 70, 250));
    player.setOutlineThickness(4);
    player.setOutlineColor(sf::Color(100, 50, 250));
    player.setPosition(200, 200);

    while(window.isOpen())
    {
        sf::Event event;

        while(window.pollEvent(event))
        {
            if(event.type == sf::Event::Closed || sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
            {
                window.close();
            }
            //MOOVING PLAYER////////////////////////////////////////
            // moving our player to the right                     //
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)){      //
                                                                  //
                                                                  //
                player.move(3, 0);
            }
            // moving our player to the left
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Q)){
                player.move(-3, 0);
            }
            // moving our player to the UP
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Z)){
                player.move(0, -3);
            }
            // moving our player to DOWN
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)){
                player.move(0, 3);
            }
        }

        window.clear();
        window.draw(player);
        window.display();
    }

    return 0;
}

【问题讨论】:

标签: c++ sfml


【解决方案1】:

我假设您的 player.move() 方法只是将偏移量添加到玩家位置。这意味着您的对象将始终以相同的恒定速度移动(假设帧速率恒定)。相反,您想要的是有一个加速度来更新每一帧的速度。

这是基本的想法(对于一个方向;y 方向会相应地工作,尽管使用向量会更好):

  • 为您的对象提供速度和加速度。
  • 如果按住某个键,则将加速度设置为常数项,否则将其设置为零。
  • 在每一帧中,将timestep * acceleration 添加到速度。
  • 在每一帧中,将timestep * velocity 添加到对象位置。
  • 在每一帧中,将速度乘以某个衰减因子,例如 0.99

这是假设您有一个固定的时间步长(例如,60 fps 的 1/60 秒)。 Timestepping 稍微高级一些,我会推荐你​​this article on the topic

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    相关资源
    最近更新 更多