hello, a while back we discussed how the FPSAnimator is working with java’s Timer and TimerTask and found out that they work with Object.wait() which is only millisecond accurate.
for games high-precision accuracy is very important, so System.currentMillis() is just not doing the job, so System.nanoTime() would be better, IMO.
here is a small class which targets a certain framerate and uses nanoSecond precision. we have been using it for quite a while now in our game and are very satisfied.
please note that it has far less features than the FPSAnimator that comes with jogl, but maybe it is useful for someone of you:
package com.avaloop.papermint.common;
import javax.media.opengl.GLAutoDrawable;
/**
* this is a nanotime-precision animator
* @author emzic
*/
public class NanoAnimator implements Runnable {
private GLAutoDrawable drawable;
private Thread thread;
private float targetfps;
private long targetduration;
private boolean keeprunning;
public NanoAnimator(GLAutoDrawable drawable) {
this.drawable = drawable;
setTargetfps(999);
}
public void start() {
if (thread == null || thread.isAlive()) {
keeprunning = true;
thread = new Thread(this, "NewAnimator");
thread.start();
}
}
public void stop() {
keeprunning = false;
}
public void run() {
while(keeprunning) {
try {
long t1 = System.nanoTime();
drawable.display();
long t2 = System.nanoTime();
long duration = t2 - t1;
while (duration < targetduration) {
Thread.yield();
t2 = System.nanoTime();
duration = t2 - t1;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public float getTargetfps() {
return targetfps;
}
public void setTargetfps(float targetfps) {
this.targetfps = targetfps;
targetduration = (long) ((1f / targetfps) * Timing.NANOSECONDS);
}
}
feedback appreciated. i dont know if the while-Thread.yield loop is a good idea.