game-programming-patterns icon indicating copy to clipboard operation
game-programming-patterns copied to clipboard

sleep() missing in loop example "play catch up"?

Open mikehaertl opened this issue 2 years ago • 4 comments

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: game-loop-fixed

According to this image I would expect a call to sleep() in the inner loop. Could it be missing?

mikehaertl avatar Mar 14 '22 08:03 mikehaertl

while (lag >= MS_PER_UPDATE) /// ensures a certain time (MS_PER_UPDATE) has passed, and sleep isn't required { update(); lag -= MS_PER_UPDATE; }

Bilalmirza avatar Mar 14 '22 09:03 Bilalmirza

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?

mikehaertl avatar Mar 14 '22 13:03 mikehaertl

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/

Bilalmirza avatar Mar 14 '22 15:03 Bilalmirza

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:

game-loop-simple

mikehaertl avatar Mar 16 '22 10:03 mikehaertl