Hello, I'm developing a simple 2D game in Java, everything works fine. To find the correct FPS refresh/redraw/update, I used currentTimeMillis to find the difference.
The problem is that currentTimeMillis sometimes returns negative values, and the Thread.sleep will throw exception (java.lang.IllegalArgumentException: timeout value is negative)
What I did was to put a while in my game and while currentTimeMillis <= -1 check again until its over, then sleep.
Code sample:
private void gameLoop(){
// Find FPS
long FPS = 40;
long beginTime = System.currentTimeMillis();
while(beginTime < -1){
beginTime = System.currentTimeMillis();
}
while(!done){
// Sleep
try{
beginTime += FPS;
long currTime = System.currentTimeMillis();
while(currTime < -1){
currTime = System.currentTimeMillis();
}
difference = (beginTime - currTime);
// Should be (currTime - beginTime)
Thread.sleep(difference);
}catch (Exception e){
e.printStackTrace();
}
// RENDER GAME
renderGame();
}
JOptionPane.showMessageDialog(null, "Game Over\nYou Died.");
System.exit(0);
}// end gameLoop()
When the game starts, this works fine, but sometimes I still get the Exception. Is there a better way? I still think it´s strange that it´s returning a negative value.