LWJGL 3 Main Game Loop Tutorial Image LWJGL 3 Main Game Loop Tutorial

The code featured below is an example of how you create a game loop that is limited to 60 frames per second. This is useful if you have implemented update functions that are bounded by the number of times they are called rather than based on time between updates. 

The Code

public void run(){
    init();
    long lastTime = System.nanoTime();
    double delta = 0.0;
    double ns = 1000000000.0 / 60.0;
    long timer = System.currentTimeMillis();
    int updates = 0;
    int frames = 0;
    while(running){
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        if (delta >= 1.0) {
            update();
            updates++;
            delta--;
        }
        render();
        frames++;
        if (System.currentTimeMillis() - timer > 1000) {
            timer += 1000;
            System.out.println(updates + " ups, " + frames + " fps");
            updates = 0;
            frames = 0;
        }
        if(glfwWindowShouldClose(window) == GL_TRUE){
            running = false;
        }
    }

    cleanup();
}
Elliot Forbes

Elliot Forbes
Twitter: @Elliot_f

Hey, I'm Elliot and I've been working on TutorialEdge for the last 4 years! If you have any tips or suggestions as to how I can make it better, please let me know in the suggestion box below!