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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| 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

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.
