How would I stop my game loop from running at thousands of FPS?

Hey,

For the past few months I’ve been messing around on a little project of mine and now I’m just getting to the point where I can start using the game loop again. I haven’t even looked at this loop in a few months so I’m not sure how to fix it up the way I want just yet. Could someone explain how I could go about limiting the FPS to stop it from running at a few thousand FPS?

public void run() {
		long lastTime = System.nanoTime();
		long timer = System.currentTimeMillis();
		final double NANO_SECONDS = 1000000000.0 / 60.0;
		double delta = 0.0;
		int frames = 0; // (FPS)Counts how many frames can be rendered per second.
		int updates = 0; // Counts how many times update(); can be called per second.
		
		new TESTING();

		while (running) {
			long now = System.nanoTime();
			delta += (now - lastTime) / NANO_SECONDS;
			lastTime = now;
			while(delta >= 1)
			{
				updateLogic();
				updates++;
				delta--;
			}
			renderScreen();
			frames++;
			
			if((System.currentTimeMillis() - timer) > 1000)
			{
				timer += 1000;
				FRAME.setTitle(updates + "UPS, " + frames + "FPS");
				updates = 0;
				frames = 0;
			}
		}
		stop();
	}

I’m fairly sure that I based this game loop off of TheCherno’s youtube tutorials but it was quite a while back so I’m not sure.

Thanks in advance for any replies.

Benny has it covered quite nice here. :wink:

The question is why would you want to limit your FPS? If it’s for regulating how fast the actual game runs, then you’re approaching it from the wrong angle. If it’s because of processor starvation, you would probably do well to add a Thread.yield() statement in your loop. The game loops article is fairly comprehensive and should get you back on track no matter what your chosen approach is.


//D.T = System.nanoTime();
	static private void Syncronize(int fps){
		long pred_Frame_Time = 1000L * 1000 * 1000 / fps;
		long next_Frame_Start_Time = pred_Frame_Time + Frame_End_Nanos_Syn;
		long curent_Time = D.T();
		long dif_Time_In_Nano = next_Frame_Start_Time - curent_Time - 100000;
		
		if(dif_Time_In_Nano > 0){
			long mily_Sleap = dif_Time_In_Nano / 1000000;
			int nano_Sleap = (int) (dif_Time_In_Nano % 1000000);
			try {
				Thread.sleep(mily_Sleap, nano_Sleap);
			} catch (InterruptedException e1){
				e1.printStackTrace();
			}
		}
		Frame_End_Nanos_Syn = D.T();
	}

If your using Slick, you can use:

VSync - Sets FPS to monitor refresh rate - more here

appGameContainer.setVSync(true);

Directly set FPS rate - Sets the FPS rate directly, at, say 60

appGameContainer.setTargetFrameRate(60);

As for vanilla Java or LWJGL, these articles may help:



http://lwjgl.org/wiki/index.php?title=LWJGL_Basics_4_(Timing)
http://www.koonsolo.com/news/dewitters-gameloop/

Finally, it depends on the type of game you’re making. If it’s really, really simple then this may be a good idea - otherwise it might be better to leave it as it is :wink: