Movement Without Framerate Limit C++ SFML

拟墨画扇 提交于 2019-11-30 10:04:02

You should pass the time that has elapsed since the last frame to the object that needs to be drawn, and then calculate the space the object has to move, like this:

sf::Clock clock;
int speed = 300;


//Draw func that should be looped
void Draw()
{
    sf::Time elapsedTime = clock.restart();
    float tempSpeed = elapsedTime.asSeconds() * speed;
    drawnObject.move(tempSpeed, 0);
    drawnObject.draw(window);
}

This way, the 'drawnObject' will move 300 (pixels?) per second to the right regardless of the FPS

@Waty's answer is right, but you might want to use fixed time step.

Take a look at the SFML Game development book source code. Here's the interesting snippet:

const sf::Time Game::TimePerFrame = sf::seconds(1.f/60.f);

// ...

sf::Clock clock;
sf::Time timeSinceLastUpdate = sf::Time::Zero;
while (mWindow.isOpen())
{
    sf::Time elapsedTime = clock.restart();
    timeSinceLastUpdate += elapsedTime;
    while (timeSinceLastUpdate > TimePerFrame)
    {
        timeSinceLastUpdate -= TimePerFrame;

        processEvents();
        update(TimePerFrame);

    }

    updateStatistics(elapsedTime);
    render();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!