0

I am trying to follow a tutorial on creating a game in Java but I am having trouble understanding the game loop.

I do not understand the purpose of this delta variable.

Any help is appreciated.

public void run() {
    long lastTime = System.nanoTime();
    final double amountOfTicks = 60.0;
    double ns = 1000000000 / amountOfTicks;
    double delta = 0;

    while(running) {
        long now = System.nanoTime();
        delta += (now - lastTime) /ns;
        if(delta >= 1) {
            tick();
            delta --;
        }
    }
}
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
J.Ramsey
  • 13
  • 3

2 Answers2

0
  1. Understand what a nanosecond is. A nanosecond is 1 billionth of a second; one second = 1000000000 nanoseconds.
  2. 1 billion divided by amountOfTicks gives the number of ticks in a billion nanoseconds (i.e. ticks in a second).
  3. In Java, the comparison double value to an integer value results in a double value. The test if (delta >= 1) checks if delta is greater than one second's worth of ticks.
  4. If one second's worth of ticks have not passed, do nothing.
  5. If one second's worth of ticks have passed, call tick and remove one second from delta.
  6. Note that delta is an accumulation of ticks.

This is a great example of a busy loop, which usually indicates an incompetent developer.

The purpose of the code appears to inform future maintenance developers that the author is an incompetent developer.

Edit As noted. #2 is number of nanoseconds per tick.

DwB
  • 37,124
  • 11
  • 56
  • 82
  • #2 is wrong. 1000000000 ns/s / 60 ticks/s = 16666666.6666... ns/tick, not "number of ticks in a second", because you already know that number (60). – Andreas Apr 27 '18 at 19:25
-1

This seems to be a way to execute the game logic at a predetermined frames-per-second rate independent of the actual speed of the CPU. I would expect the tick () function is where a cycle of game loop is executed.

Nicholas Hirras
  • 2,592
  • 2
  • 21
  • 28