Home > OS >  The game loop designing
The game loop designing

Time:06-13

There is the simple game loop proposal:

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();
}

I think that the solution do have one serous drawback. Let's assume that (in some rather very uncommon case) the lag is about as huge as 3 seconds. In such a case if the MS_PER_UPDATE == 16msec (1/(60 fps)) the update function in internal loop (while (lag >= MS_PER_UPDATE)) will run 180 times! Taking into consideration that the update function may take some not very large but still decent time needed to there will be a significant.

Wouldn't the following:

double previous = getCurrentTime();
double lag = 0.0;
while (true)
{
  double current = getCurrentTime();
  double elapsed = current - previous;
  previous = current;
  lag  = elapsed;

  processInput();

  if (lag >= MS_PER_UPDATE)
  {
    update(lag);
    lag = 0;
  }

  render();
}

solution be better?

Here instead of calling the render function 180 time I call the render only ONCE but with lag as a parameter. And inside the render the game objects are updated (say moved) proportionally to the vale of the passed lag so if for. e.g. the lag was 5 times > then the default fps (1/60) we just move all objects 5x instead of 1x?

CodePudding user response:

The whole point of games loops with fixed-size step is to decouple rendering and physics to retain stability, determinism in face of variable FPS.

You cannot simply update physics with 5 times larger step and expect it to be equal to updating 5x with the original step. That is simply not possible. With high enough step, numerical calculations will break down - fast collisions will be missed, objects will clip into each other, some might "explode".

So yes, you can go back to variable-sized time step of course, but you will get back all the drawbacks due to which it was abandoned.

  •  Tags:  
  • c
  • Related