I use this game loop:
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
| inf FPS=20; int fps_delay=1000/FPS. long time=System.currentTimeMillis(),elapsed=0,fps_error=0; while (thread!=null) { elapsed=System.currentTimeMillis()-time; time=System.currentTimeMillis(); update((int)elapsed); repaint(); serviceRepaints(); try { long t=System.currentTimeMillis(); elapsed=fps_delay-(t-time)-fps_error; if (elapsed>0) { thread.sleep(elapsed); fps_error=(System.currentTimeMillis()-t)-elapsed; } else { thread.yield(); fps_error=0; } } catch (Exception ex) { } } |
I use fps_error to correct "time errors" generated by thread.sleep(), without it the framerate is a bit worse if the sleep has not so much accuracy.
Maybe thread.yield() could be replaced by thread.sleep(1) to be sure it permit others threads execute, possibly we will lost some fps, but it will work better.
I use it in my qames for a lot of phone models, i think it works well, but suggestions are appreciated!!

Best regards