Movement Without Framerate Limit C++ SFML
Asked Answered
J

2

5

I'm working an making a game in SFML right now, but I am getting stuck on movement without a framerate limit. Right now the only way I have figured out how to get consistent framerate on all computers is by using

window.setFramerateLimit(30);

I want to find a way to not have a framerate cap so it does look better on better computers and so that if anybody has a really slow computer, they can still play the game. What would be the best way to do this.

Julio answered 19/8, 2013 at 3:42 Comment(1)
I highly recommend book SFML Game Development which has a chapter on this. You need to pass a sf::Time deltaTime (which is the time since the last frame) to each update function, and adjust your movement distances by this delta time.Dunfermline
O
7

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

Oidea answered 19/8, 2013 at 18:45 Comment(1)
This is right, but it might causes problem with high frame rate when updating with an elapsed time to small, causing some rounding errors with float. I'm not going to go into the details, here's a useful link: gafferongames.com/game-physics/fix-your-timestepRemote
R
6

@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();
}
Remote answered 17/9, 2013 at 10:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.