LWJGL 3 Main Game Loop Tutorial Image

LWJGL 3 Main Game Loop Tutorial

Table Of Contents

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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();
}
Was This Post Helpful?
Submit a PR: Edit on Github