-1

Consider this Game Loop:

        double nextTime = (double)System.nanoTime() / 1000000000.0;
        while(runFlag)
        {
            double currTime = (double)System.nanoTime() / 1000000000.0;
            if(currTime >= nextTime)
            {
                nextTime += delta;
                update();
                draw();
            }
            else
            {
                int sleepTime = (int)(1000.0 * (nextTime - currTime));
                if(sleepTime > 0)
                {
                    try
                    {
                        Thread.sleep(sleepTime);
                    }
                    catch(InterruptedException e)
                    {
                    }

How should I calculate an appropriate value of delta (the time that has to pass before the next update and render). I have seen it been calculated different ways but I am still not sure how or what exactly is really going on. This is a fixed time step loop, so for instance if i wanted to calculate delta for a constant fps of 30 of 60, what would I have to set it as and why? I am unable to grasp some of the explanations I have come across on the Internet. Thanks.

imgolden62
  • 396
  • 2
  • 5
  • 14

1 Answers1

2

If you want to produce a particular frame per second rate, consider the following:

  1. You want to produce a new frame every 1/frames-per-second seconds.
  2. It may take you p seconds to produce a frame (processing)
  3. The "free time" between frame productions, delta, would be 1/frames-per-second - p

You might use the following pseudo-code:

frameTimeMilliseconds = 1000 / frames-per-second

Loop(condition) {
  startFrameTime = system current time in milliseonds
  do frame production
  endFrameTime = system current time in milliseconds
  sleepTime = frameTimeMilliseconds - (endFrameTime - startFrameTime)

  sleep for sleepTime milliseconds
}

You may want to handle the condition where the actual frame production time is longer than the required frame production time (i.e. where sleepTime is <= 0)

ErstwhileIII
  • 4,829
  • 2
  • 23
  • 37
  • 1
    Ok, so for instance: Desired FPS: 30. So 1/30 would give me the time it takes for my computer to produce one frame at a desires FPS. But how do I find p? @ErtswhileIII – imgolden62 Jan 02 '15 at 18:23