Imagine if you had a loop that looked like this:
while (!quit)
{
//Do stuff
clock.restart();
float delta = clock.getElapsedTime().asSeconds();
}
The goal of
delta is to measure the time it takes to complete
//Do stuff. The clock gets reset to 0 and then you measure it.
delta will always be 0 or near 0.
In order, you're basically doing:
- Do stuff
- Restart clock
- Take amount of time since the restart of the clock
Of course, in your code, you do poll events between the time you restart and the time you get the time elapsed, but your goal is to measure the entire game loop, not just the time it takes to poll events.
But if you rearranged it like this:
while (!quit)
{
//Do stuff
float delta = clock.getElapsedTime().asSeconds();
clock.restart();
}
Now
delta is the amount of time it took for whatever is in place of
//Do stuff to occur. In order, you're now doing this:
- Restarting clock
- Doing stuff
- Taking amount of time since clock was restarted
As Hapax suggested, it may be easier to just do:
while (!quit)
{
//Do stuff
float delta = clock.restart().asSeconds();
}
Because
sf::Clock::restart returns the time elapsed on the clock before it was restarted.
But as I mentioned earlier, you may want to do something like this:
const float timestep = 1.0f / 60.0f; //Update at 60hz
float accumulator = 0.0f;
while (!quit)
{
accumulator += clock.restart().asSeconds();
while (accumulator >= timestep)
{
accumulator -= timestep;
//Do stuff
}
}
And just move your circle at a fixed speed (
100.0f/60.0f per update).
As for why you'd want to do this, look at:
http://gafferongames.com/game-physics/fix-your-timestep/http://gameprogrammingpatterns.com/game-loop.html