0
\$\begingroup\$

I wonder if this gameloop in Java is accurate to give around 60 frames a second, is it?

public void run() {
    long then = System.nanoTime();
    long targetFPS = 60;
    Timer timer = new Timer();

    while(running){
        long now = System.nanoTime();
        long updateLength = now - then;
        long update = updateLength / targetFPS;
        then = now;
        System.out.println(update);
        if(update >= 16){
            render();
            tick();
            System.out.println(updateLength);
        }
    }
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Measure it (filler) \$\endgroup\$
    – Bálint
    Apr 25, 2017 at 11:35
  • 1
    \$\begingroup\$ Also do you not generally tick then render? \$\endgroup\$
    – lozzajp
    Apr 25, 2017 at 11:42

1 Answer 1

2
\$\begingroup\$

It isn't.

This keeps the CPU running constantly, which uses a lot of power. Also, system.nanotime can be really slow on certain PCs. Instead try something like:

long time = System.currentTimeMillis();
// Do your stuff
Thread.sleep(Math.max(0, time - 16));
run();

This doesn't exactly produce 60 fps, because that requires 16,66 milliseconds between frames, but it's really close.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .