Best [Smallest] Consistent Timing?

Hi guys.

I was wondering what is the best method you’ve found so far for keeping consistent timing in a 4K game. I’ve looked at the source code for several 4K games and most seem to employ different approaches. Any tips on this would be greatly appreciated.

I use System.nanoTime() to compute the exact duration of the most recent frame. I then compute a time factor from frame duration, which is applied in all computations. This way, you get approximately performance-independent game behavior. Pseudocode example:


// Initialize timer
timer=nanotime
// Game loop
while game running
  // Update timer
  timer=nanotime-timer
  // Compute delta (this is a float or double!)
  delta=nanotimer/10e6
  // Example application: Movement
  exampleposition+=examplevelocity*delta

Note: You have to be a bit careful when dealing with derivates (e.g. accelleration), know your calculus :slight_smile:

hth Wolfgang

“I’m a ****ing starship, I’m allowed to cheat!”
GCU Arbitrary, Culture Craft

I do mine slightly differently I have a set game logic frame rate and undetermined paint frame rate. This allows me to not use a delta multiplier and instead just hard coded values thus reducing the code needed.

you can probably use nanotime instead of currentTimeMillis(), I used it for legacy JVMs

e.g. for a frame rate of 40 fps



long lastTime=System.currentTimeMillis();

while (game alive)
{
      while (lastTime<System.currentTimeMillis())
      {
             lastTime+=25;

             //perform game logic

      }

       // draw graphics

       Thread.yield();
}

Thanks very much for the replies guys.
I’ll try out moogie’s approach as I was using the delta before.

It is a good idea to use nanotime, no matter which timing scheme you apply, because currentTimeMillis is very unprecise under Windows and will limit you to 20fps under certain (not so uncommon) system/os combinations.

Moogie, I’ll try out your approach in my Elite clone, hadn’t though about it in years due to the shortcomings of currentTimeMillis but with precise timing it should work for simulations with higher precising requirements, too.