# Java game loop delta not working

Hello I have game loop where I can change framerate. But when I change framerate to other, delta time not working fine. For example when framerate is lower everything is faster.

Here is game loop:

double delta = 0.0;
private double framerate = 60.0;
private double frameTime = 1.0/framerate;

public void run() {
runFlag = true;
int frames = 0;
double frameCounter = 0;

double lastTime = (double)System.nanoTime()/(double)1000000000L;
double unprocessedTime = 0;

while(runFlag) {
boolean render = false;

double startTime = (double)System.nanoTime()/(double)1000000000L;
double passedTime = startTime - lastTime;
lastTime = startTime;

unprocessedTime += passedTime;
frameCounter += passedTime;

while(unprocessedTime > frameTime) {
render = true;

unprocessedTime -= frameTime;

tick();

delta = frameTime;

if(frameCounter >= 1.0) {
this.frames = frames;
Display.setTitle("  FPS: "+frames+"  DELTA: "+(float)delta);

frames = 0;
frameCounter = 0;
}
}
if(render) {
render();

frames++;
} else {
try {
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Display.update();
}
destroy();
}


What is wrong with this game loop ?

• where do you declare delta variable ? – dimitris93 Feb 1 '15 at 16:47
• double delta is over the constuctor so I don't write it. – Suak Feb 1 '15 at 17:25

Your delta will be always equal to 1/60, but that's not what delta time is. Delta is the time that passed between current and previous call. Here's an example:

double delta;
double currentTime, lastTime;

while (doingStuff)
{
currentTime = getCurrentTime() //You have to define this method somewhere

delta = currentTime - lastTime;

lastTime = currentTime;
}


In this example, delta is the difference between time of last and current iteration of the loop.

The "delta" you calculated is the perfect time you want between frames. And there's a giant difference between the time you want, and the time you actually have.

• where i can put render ? – Suak Feb 1 '15 at 19:57
• I see you just copy code. I don't encourage that. You should be able to figure it out yourself. Only thing you have to change is the delta time calculation. It's not that hard. – Mr. Nerd Feb 1 '15 at 20:07