0
\$\begingroup\$

I am creating a simple game using Java. I'm not using any game library. I just want to know if it is okay to call Thread.sleep(40) before calling repaint().

public void run() {
    while(isGameRunning) {
        try {
            Thread.sleep(40);
            repaint();
        }
        catch(Exception e) {
        }
    }
}

or should I use:

private long last_time = System.nanoTime();
private double ns = 1000000000/25D;
private double delta = 0;
@Override
public void run() {
    while(Universe.IsGameRunning) {
        long time  = System.nanoTime();
        delta += (int)(time - last_time)/ns;
        last_time = time;
        System.out.println(delta);
        if(delta>=1) {
            repaint();
            delta--;
        }
    }
}

The code below has more CPU and RAM usage than the first one. Can you explain to me how 'Delta Timing' actually works?

enter image description here

\$\endgroup\$
1
\$\begingroup\$

Delta timing is almost always the better choice.

The idea behind it is that it gives you the exact number of milliseconds since the last frame computation cycle completed.

Let's say it only takes 10ms to compute the frame.

In your first example, you specify a 40m/s delay. This means, that 30ms for each frame will be spent doing nothing, and at best, you will get 25 fps (1000/40).

In your second example, you are computing the frame, then immediately starting again. This means that, as it only took 10ms to compute your frame, you are actually getting 100 frames per second. This will be 4 times as smooth when it comes to animation, and will ensure that no cpu time is wasted.

I will add that with smaller, more discrete timesteps between frames, collision detection becomes more accurate, and less likely to allow objects to tunnel through each other.

\$\endgroup\$
  • \$\begingroup\$ Frame time is also most likely going to be variable, depending on how much is going on in each frame. Sleeping for a fixed time cannot account for that, so even if you do wish to sleep, you're going to have to end up measuring time anyway. \$\endgroup\$ – Maximus Minimus Apr 8 '17 at 17:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.