Hello everybody,
this is a very nice forum.
I have got a problem with my run - game loop. The first 1-2 seconds it has more than 1800 FPS and after that it is about 300, althoug I set the target FPS to 60.
I tested this loop and animated a polygon which moves from x:0 y:0 diagonal down. After the FPS break from about 1800 to 300 it runs with full speed out of sight
These are the deltas at that special moment:
0.15598080623923224
1.5791460031658402
public void run() {
final int MAX_FRAME_SKIPS = 5;
final int NO_DELAYS_PER_YIELD = 16;
final int TARGET_FPS = 60;
final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;
long beforeTime, afterTime, timeDiff, sleepTime;
long overSleepTime = 0L;
long excess = 0L;
long period = 1000 / TARGET_FPS;
int noDelays = 0;
int fps = 0;
int lastFpsTime = 0;
double delta = 1.0;
beforeTime = System.nanoTime();
isRunning = true;
while (isRunning) {
update(delta);
render();
paintScreen();
afterTime = System.nanoTime();
timeDiff = afterTime - beforeTime;
sleepTime = (period - timeDiff) - overSleepTime;
delta = timeDiff / ((double) OPTIMAL_TIME);
lastFpsTime += timeDiff;
fps++;
if (lastFpsTime >= 1000000000) {
printFps = fps;
lastFpsTime = 0;
fps = 0;
}
if (sleepTime > 0) {
try {
Thread.sleep(sleepTime / 1000000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
overSleepTime = (System.nanoTime() - afterTime) - sleepTime;
} else {
excess -= sleepTime;
overSleepTime = 0L;
if (++noDelays >= NO_DELAYS_PER_YIELD) {
Thread.yield();
noDelays = 0;
}
}
beforeTime = System.nanoTime();
int skips = 0;
while ((excess > period) && (skips < MAX_FRAME_SKIPS)) {
excess -= period;
update(delta);
skips++;
}
}
}
I really hope, that somebody could help me. Maybe to improve my loop as well.
Thank you very much in advance,
Best regards, Kronos.
edit:
embarassing moment :persecutioncomplex:
I used myPolygon.translate(x, y);
I donât know what this does exactly, but not what I wanted it to do. The loop seems to be okay, beside that it does not reach my target FPS which is set to 60.