0

I keep getting a lot of "Delta: 0.0"s in my console and ever few lines I get something like "Delta: 9.999275207519531E-4", what's happening?

    Timer timer = new Timer();
    float lastTime = 0.0f;
    timer.resume();
    while (!Display.isCloseRequested())
    {
        timer.tick();
        System.out.println("Delta: " + (timer.getTime() - lastTime));

        lastTime = timer.getTime();

        Display.update();
    }

    Display.destroy();
DotNet NF
  • 805
  • 1
  • 6
  • 14

2 Answers2

1

Don't ever use java's Timer class in your game loops. It isn't precise enough to use reliably. Instead, check out this link to see a couple of reliable game loops written in java.

Flafla2
  • 545
  • 7
  • 12
0

One little note, just a warning. Your timing mechanism is flawed a bit.
Considering this code runs line by line as it is written, you'll "loose" time. This

System.out.println("Delta: " + (timer.getTime() - lastTime));
lastTime = timer.getTime();

code does the following:
1. Getting current time.
2. Doing some math.
3. Calling String constructor.
4. Performing String concatenation.
5. Writing current time to the lastTime variable.

Note that current time in the 1 and 5 cases are different. That means that this time is "lost" from the "Delay: xx" output.

If you continue to use (timer.getTime() - lastTime) technics in your code for the purpose of getting time passed from the previous iteration, you will surely run into problem where different events thinks that time passed from the previous iteration is different. I recommend you to use the following code for timing:

private double delta;
private long timing;

public void updateTime()
{
    long newTime = System.nanoTime();
    this.delta = (newTime - this.timing) / 1_000_000_000.0;
    this.timing = newTime;
}

public double getDelta() {
    return this.delta;
}

where updateTime() is called once per cycle and getDelta() is called every time you want to get time passed from the previous iteration.

Chechulin
  • 2,426
  • 7
  • 28
  • 35