public void run() {
long desiredFPS = 500;
long desiredDeltaLoop = (1000*1000*1000)/desiredFPS;
long beginLoopTime;
long endLoopTime;
long currentUpdateTime = System.nanoTime();
long lastUpdateTime;
long deltaLoop;
int deltaMs = 0;
while(isRunning){
beginLoopTime = System.nanoTime();
window.panel.repaint();
lastUpdateTime = currentUpdateTime;
currentUpdateTime = System.nanoTime();
onUpdateGame(deltaMs);
deltaMs = (int) ((currentUpdateTime - lastUpdateTime)/(1000*1000));
endLoopTime = System.nanoTime();
deltaLoop = endLoopTime - beginLoopTime;
if(deltaLoop > desiredDeltaLoop){
//Do nothing. We are already late
} else {
try{
Thread.sleep((desiredDeltaLoop - deltaLoop)/(1000*1000));
} catch (InterruptedException e) {
//Do nothing
}
}
}
}
Hi,
I'm trying to implement a 2D game using the Java2D API. I'm using the code posted below in my run() method of my main thread to limit the framerate to a specific maximum.
Objects are moved by a distance calculated from the elapsed time between frames. The movement of said objects, however is noticeably jerky.
Could the problem be to do with the method used below? I've seen this type of thing used in several introductory examples to games in Java.
Many thanks.