game-programming-patterns
game-programming-patterns copied to clipboard
sleep() missing in loop example "play catch up"?
I try to wrap my head around the final code example on the page on game loops:
double previous = getCurrentTime();
double lag = 0.0;
while (true)
{
double current = getCurrentTime();
double elapsed = current - previous;
previous = current;
lag += elapsed;
processInput();
while (lag >= MS_PER_UPDATE)
{
update();
lag -= MS_PER_UPDATE;
}
render();
}
In the text it says:
We then have an inner loop to update the game, one fixed step at a time, until it’s caught up.
I fail to see any fixed time step here. How often update()
is called is only limited by how fast the underlying machine is. So a faster machine will give more updates than a slower machine. This throws us back to non-deterministic behavior as described a chapter before.
It also doesn't match with the diagram, where there's a clock above the update()
box:
According to this image I would expect a call to sleep()
in the inner loop. Could it be missing?
while (lag >= MS_PER_UPDATE) /// ensures a certain time (MS_PER_UPDATE) has passed, and sleep isn't required { update(); lag -= MS_PER_UPDATE; }
I still don't quite get it. Here's an example with some numbers:
- MS_PER_UPDATE = 10
- update() takes 5
- render() takes 20
In the first cycle there's no update()
(lag = 0).
In the second cycle lag = 25
(5 + 20) so I see 2 calls to update()
in a row and there's no pause in between.
In the third cycle there will even be 3 calls (lag = 30
) with no break in between. How is this considered fixed time steps?
since render is not called when catching up. The Displayed objects will work correctly.
its covered in.
https://gameprogrammingpatterns.com/game-loop.html
and more detail in here
https://gafferongames.com/post/fix_your_timestep/
My problem was that all the statements and the diagram relate to game time, not real time. Not sure if this could be made more clear. I still find the diagram above misleading, though, because IMO this first diagram here does not relate to game time but real time: