How do I calculate the time between frames on Android? I'm using this for the thread:
public class GameThread extends Thread
{
private int FPS = 30;
private double averageFPS;
private SurfaceHolder surfaceHolder;
private Game gamePanel;
public boolean running;
public static Canvas canvas;
public static double deltaTime;
public GameThread(SurfaceHolder surfaceHolder, Game gamePanel) {
super();
this.surfaceHolder = surfaceHolder;
this.gamePanel = gamePanel;
}
@Override
public void run() {
long startTime;
long timeMillis;
long waitTime;
long totalTime = 0;
int frameCount =0;
long targetTime = 1000/FPS;
while(running) {
startTime = System.nanoTime();
canvas = null;
//try locking the canvas for pixel editing
try {
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
this.gamePanel.tick();
this.gamePanel.render(canvas);
}
} catch (Exception e) {
} finally {
if(canvas!=null)
{
try {
surfaceHolder.unlockCanvasAndPost(canvas);
} catch(Exception e){
e.printStackTrace();
}
}
}
timeMillis = (System.nanoTime() - startTime) / 1000000;
waitTime = targetTime-timeMillis;
try{
sleep(waitTime);
} catch (Exception e) {
}
deltaTime = waitTime;
totalTime += System.nanoTime() - startTime;
frameCount++;
if(frameCount == FPS)
{
averageFPS = 1000/((totalTime/frameCount)/1000000);
frameCount =0;
totalTime = 0;
System.out.println(averageFPS);
}
}
}
public void setRunning(boolean b)
{
running=b;
}
}
I tried doing it like in normal Java, but it didn't work (it only lead to a crash).