logo

Java - GameLoop

GameLoop Template

I've seen many variants of the code below, this is the snippet I keep falling back on.

long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int ticks = 0;
int fps = 0;
 
while(running){
   long now = System.nanoTime();
   delta += (now - lastTime) / ns;
   lastTime = now;
   while(delta >= 1){
      update();
      ticks++;
      delta--;
   }
   draw();
   fps++;
 
   if(System.currentTimeMillis() - timer > 1000){
      timer += 1000;
      System.out.format("FPS: %d  Ticks: %d", fps, ticks);
      fps = 0;
      ticks = 0;
   }
}
 
 
/* ... */
 
void update()
{ ... }
 
void draw()
{ ... }