I have a FPS function that:
private static void runGameFPS2() {
long beginTime; //The time when the cycle begun
long timeDiff; //The time it took for the cycle to execute
int sleepTime; //ms to sleep (< 0 if we're behind)
int fps = 1000 / 40;
beginTime = System.currentTimeMillis();
//Update game state
updateGame();
//Render state to the screen
renderScreen();
//Calculate how long did the cycle take
timeDiff = System.currentTimeMillis() - beginTime;
//Calculate sleep time
sleepTime = fps - (int)(timeDiff);
if (sleepTime > 0) {//If sleepTime > 0 we're OK
try { Thread.sleep(sleepTime); }catch(InterruptedException e){}
}else{
//suppose will not be
}
}
public static void main(String[] args){
while(true){ runGameFPS2(); }
}
When I run my code, Java works at different speeds on same computer or on different computers.
How can I write a consistent code, that Java will always work "same time" (for example 40 FPS) on mycomputer or any computer?
Note: suppose sleepTime will never be sleepTime < 0
