Hi,
I am practising a little bit now by making a pac-man game in Java2D. Everything is working pretty well except calculating the frames per second.
This is my run() method which continuously calls the gameloop update(Graphics2D gfx) Here you can see my futile attempt at calculating the FPS
public void run() {
while (isRunning) {
long starttime = System.currentTimeMillis();
try {
Graphics2D gfx = (Graphics2D)getGraphics();
update(gfx);
Thread.currentThread().sleep(25);
}
catch (InterruptedException ex) {
System.out.println("Something went seriously wrong!");
}
long duration = System.currentTimeMillis() - starttime;
double fps = 1/(duration*0.001);
System.out.println("FPS: " + fps);
}
}
To me it seems this should work, however, with a sleep of 25 milliseconds, the fastest FPS I should be able to get is 40 fps
The strange thing is, my FPS keeps on flipping between 31.5 and 61.2 fps when I make the sleep longer, like 50, it will switch between 15.8 and 16.1 continuously.
If I put the sleep on 1 ms, it still switches between 31.5 and 61.2 when I take out the update(gfx) it will also switch to INF next to the 31.5 and 61.2
What am I doing wrong here? Or does anyone have a way of doing this correctly?