Skip to content
Heiko Brumme edited this page Jan 29, 2015 · 4 revisions

This is a sub-part of the game loop tutorial, where we look into Time calculations.

Getting the system time

The main reason for the timer is getting the system time for your application. You should take a timer with an accuracy of at least milliseconds or even nanoseconds.
Since LWJGL3 has a GLFW port we can use glfwGetTime() for getting the time in seconds since glfwInit().

public double getTime() {
    return glfwGetTime();
}

If you don't want to use that you have also the option to use Java's System.nanoTime() and divide it by 1000000000 to get the time in seconds.

public double getTime() {
    return System.nanoTime() / 1000000000.0;
}

Calculating delta time

For calculating the delta time we have to store the system time of the last loop, which has to get initialized before starting the game loop.

double lastLoopTime;

public void init() {
    lastLoopTime = getTime();
}

With that calculating the delta time is straightforward.

public float getDelta() {
    double time = getTime();
    float delta = (float) (time - lastLoopTime);
    lastLoopTime = time;
    timeCount += delta;
    return delta;
}

You can see that there is also a timeCount variable, this is used for calculating the FPS and UPS.

FPS and UPS calculation

There are many ways for calculating FPS and UPS, but in this guide we need five variables for it:

float timeCount;
int fps;
int fpsCount;
int ups;
int upsCount;

Now whenever the game loop makes an update() we should also increment the upsCount, and after render() we increment the fpsCount.

public void updateFPS() {
    fpsCount++;
}

public void updateUPS() {
    upsCount++;
}

To refresh the FPS and UPS variables we need to update the timer after each loop. If a second has passed we can update those values.

public void update() {
    if (timeCount > 1f) {
        fps = fpsCount;
        fpsCount = 0;

        ups = upsCount;
        upsCount = 0;

        timeCount -= 1f;
    }
}

Source code

Clone this wiki locally