I wrote a tutorial on game loops on my
website. Here's the source code if that's all your interested in. I need to do a little bit of fix up (I shouldn't have used doubles to represent the time in seconds), but it should work.
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
| public abstract class GameLoop { private boolean runFlag = false; public void run(double delta) { runFlag = true; startup(); double nextTime = (double)System.nanoTime() / 1000000000.0; double maxTimeDiff = 0.5; int skippedFrames = 1; int maxSkippedFrames = 5; while(runFlag) { double currTime = (double)System.nanoTime() / 1000000000.0; if((currTime - nextTime) > maxTimeDiff) nextTime = currTime; if(currTime >= nextTime) { nextTime += delta; update(); if((currTime < nextTime) || (skippedFrames > maxSkippedFrames)) { draw(); skippedFrames = 1; } else { skippedFrames++; } } else { int sleepTime = (int)(1000.0 * (nextTime - currTime)); if(sleepTime > 0) { try { Thread.sleep(sleepTime); } catch(InterruptedException e) { } } } } shutdown(); } public void stop() { runFlag = false; } public abstract void startup(); public abstract void shutdown(); public abstract void update(); public abstract void draw(); } |