Game loop help

Hey everyone, I’ve just gotten started with java game development and i though that I’d create a simple space invaders clone to start off with. I’ve created an update and render loop and managed to render a sprite to the screen.

While i was first creating the game loop it updated 60 times per second as i was expecting and i was getting a bunch of fps. But now when I’ve started adding stuff to the render function of my game it only updates at around 55-59 times a second.

Sure this isn’t huge performance hit but i would like to know what causes this.

So if anyone feels like looking at the code here it is:

       int frames = 0;
		int ticks = 0;
		double targetTickTime = 1000000000 / 60;
		double lastUpdateTime = System.nanoTime();
		double lastFPSPrintTime = System.nanoTime();

		while (running) {
			double nowTime = System.nanoTime();
			if (nowTime - lastUpdateTime >= targetTickTime) {
				ticks++;
				tick();
				lastUpdateTime = System.nanoTime();
			}
			if (nowTime - lastFPSPrintTime >= 1000000000) {
				System.out.println("Updates: " + ticks + ", Frames: " + frames);
				ticks = 0;
				frames = 0;
				lastFPSPrintTime = System.nanoTime();
			}
			render();
			frames++;
		}

Well, you’re currently rendering as fast as you possibly can. I would recommended rendering 60 times a second as well, since rendering is usually pretty costly. I would also suggest using Thread.sleep() to eat up the time between updates instead of just letting the loop run and eat up CPU cycles. To see what I’m talking about, have a look at this article on game loops, especially the fixed timestep loop that Yields/Sleeps for the left over time.

When you say I should render 60 times per frame as well, do you mean I should just call tick() and then render()? or is there a better way of doing it?

That’s the way I do it



               long lastTime = System.nanoTime();
	       double nsPerTick = 1000000000D / 60D; //~60fps
		
		int ups = 0;
		int fps = 0;
		
		long lastTimer = System.currentTimeMillis();
		double delta = 0;
		
		while(game loop not quit blub) {
			long now = System.nanoTime();
			delta += (now - lastTime) / nsPerTick;
			lastTime = now;
			boolean renderOK = false;
			while(delta >= 1) {
				ups++;
				update();
				delta -= 1;
				renderOK = true;
			}
			if(shouldRender) {
				fps++;
				render();
			}
			if(System.currentTimeMillis() - lastTimer >= 1000) {
				lastTimer += 1000;
				System.out.println("frames: " + fps + " | updates: " + ups);
				fps = 0;
				ups = 0;
			}
		}

constantly 60 fps.

Yes. If you looked at the two best examples from the article I linked to you updating and rendering are both done before the time wasting (or waiting for the next cycle) is. The article gets a little more advanced and compensates for running slow by “dropping” frames. It does this by updating without rendering until it catches up, and then it renders.

Ok i got it working now, thanks for the helpful responses =)