I’m new to java game development, and i’ve started from development of a simple tile-based game. Anyway… I’ve got a huge problem with timing, since System.currentTimeMills do not work as it supposed to. I’ve read the cokeandcode tutorials, but I don’t want to use a JNI solution in my game.
I’ve read that “one way to deal with the inconsistency of timing on Windows is to average the change in time between frames”. And I’ve done a separate timing class:
public class LoopTimer {
private long[] loopStatistics;
private int loopsCollected = 0;
private boolean inited = false;
private long loopStart = 0;
public LoopTimer(int numLoopsForStatistics){
loopStatistics = new long[numLoopsForStatistics];
}
public LoopTimer(){
this(5);
}
public long getLoopTime(){
long loopTime = System.currentTimeMillis() - loopStart;
if (loopTime == 0){ // Sometimes after the loop the time is still zero!!!
return getAverage();
}
loopStart = System.currentTimeMillis();
if (!inited){
inited = true;
return 1;
}
if (loopsCollected == 0){
for (int i = 0; i < loopStatistics.length; i++)
loopStatistics[i] = loopTime;
loopsCollected++;
return loopTime;
}
loopStatistics[loopsCollected - 1] = loopTime;
loopsCollected++;
if (loopsCollected >= loopStatistics.length)
loopsCollected = 1;
return getAverage();
}
private long getAverage(){
long sum = 0;
for (int i = 0; i < loopStatistics.length; i++)
sum += loopStatistics[i];
long avg = (long)sum/loopStatistics.length;
if (avg <= 0)
return 1;
return avg;
}
}
Then I’ve used it like this:
while(doGameLoop){
currentFrames++;
// Update FPS
if (System.currentTimeMillis() - lastTime > 1000){
totalFrames = currentFrames;
currentFrames = 0;
lastTime = System.currentTimeMillis();
}
g = (Graphics2D)strategy.getDrawGraphics();
g.setColor(new Color(25, 25, 25));
g.fillRect(0, 0, 600, 600);
loopTime = loopTimer.getLoopTime();
System.out.println(loopTime);
gameWorld.update(loopTime);
gameWorld.draw(g);
g.setColor(new Color(230, 230, 230));
g.drawString(String.valueOf(totalFrames) + " fps", 10, 10);
g.dispose();
strategy.show();
try {
Thread.sleep(5);
} catch (InterruptedException e) {}
And when I’ve tried to run all this together i see that the mooving speed of the objects is not constant at all! Sometimes my starships start move faster (for about a second or so). Maybe there is another way to manage this probem?