Search code examples
javaframe-rategame-loop

How should I figure out what my update length (delta) should be in my Game loop in Java?


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.


Solution

  • 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)