i have a problem with deltaTime ive been using. My Code is the following:
public class Time {
public static float deltaTime = 0;
public static long frameCount = 0;
public static float fixedTime = 0;
public static float fixedDeltaTime = 0.1f;
public static float maxDeltaTime = 0.25f;
}
And now in my MainThread.java in my run() function:
while (running) {
canvas = null;
try {
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
float newTime = System.nanoTime() / 1000000000.0f;
Time.deltaTime = frameTime = newTime - currentTime;
if(frameTime > Time.maxDeltaTime)
frameTime = Time.maxDeltaTime;
currentTime = newTime;
accumulator += frameTime;
while(accumulator > Time.fixedDeltaTime)
{
this.gamePanel.update(); // where the player and my enemy gets updated
accumulator -= Time.fixedDeltaTime;
}
this.gamePanel.render(canvas);
//Perform all non-physics-related updates here
++Time.frameCount;
framesSkipped = 0; // resetting the frames skipped
timeDiff = System.currentTimeMillis() - beginTime;
// calculate sleep time
sleepTime = (int)(FRAME_PERIOD - timeDiff);
if (sleepTime > 0) {
// if sleepTime > 0 we're OK
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {}
}
while (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS) {
// we need to catch up
this.gamePanel.update(); // update without rendering
sleepTime += FRAME_PERIOD; // add frame period to check if in next frame
framesSkipped++;
}
if (framesSkipped > 0) {
Log.d(TAG, "Skipped:" + framesSkipped);
}
// for statistics
framesSkippedPerStatCycle += framesSkipped;
// calling the routine to store the gathered statistics
storeStats();
}
} finally {
// in case of an exception the surface is not left in
// an inconsistent state
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
} //end finally
}
}
in the gamePanel.update() ive got the update calls for the player and my enemy.
Now my Problem is, that at the start of my game the deltaTime is extremly high und thus my movement is very fast, because i have the following in my enemy class in the update method:
x += vX * Time.deltaTime; // velocity * deltaTime
y -= vY * Time.deltaTime;
//Log.d(TAG, "Time:"+Time.deltaTime+" x: "+x+" y: "+y);
vY -= gravity;
Am i doing it right, or is something wrong with my structure?
Thanks for any help.
You need to initialize
currentTimebefore the start of the loop. You don’t show how it’s being initialized, but my guess it starts at 0, so on the first loop iteration,deltaTimeis being set to the current time as returned bySystem.nanoTime().P.S. Is there some reason you are using
System.nanoTime()in one place andSystem.currentTimeMillis()in another? Also, consider sticking to computing everything in milliseconds (or nanoseconds) withlongvalues and eliminating the floating point calculations.