Search code examples
c++sfmlgame-looptimedelta

Implementing Delta timing in my loop


I want to implement delta timing in my SFML loop in order to compensate for other computers that choose to run my application, right now I just have

float delta = .06 

placed before my loop, but as wikipedia describes delta timing:

It is done by calling a timer every frame per second that holds the time between now and last call in milliseconds.[2] Thereafter the resulting number (Delta Time) is used to calculate how much faster that, for instance, a game character has to move to make up for the lag spike caused in the first place.[3]

Here is what I'm doing that is WRONG currently, I can't quite seem to translate the logic into syntax:

bool running=true;                                      //set up bool to run SFML loop
    double lastTime = clock.getElapsedTime().asSeconds();
    sf::Clock clock;                                        //clock for delta and controls
    while( running )
    {
        clock.restart();
        double time= clock.getElapsedTime().asSeconds();
        double delta = time - lastTime; //not working... values are near 0.0001
        time = lastTime;
        //rest of loop

Solution

  • Shouldn't it be:

    sf::Clock clock;
    while( running )
    {
        double delta =  clock.restart().asSeconds(); // asMilliseconds()
        //rest of loop
    }
    

    (I assume you do not need time and last_time)