Monday, May 16, 2016

java - Calculating delta time


I'm trying to calculate deltaTime, but it's not correct.


What's wrong in my code?


//declared outside
private long timeSinceStart = System.nanoTime() / 1000;
private long oldTimeSinceStart = 0;
public static long deltaTime = 1;

while(running)

timeSinceStart = System.nanoTime() / 1000;
deltaTime = timeSinceStart - oldTimeSinceStart;
oldTimeSinceStart = timeSinceStart;

Answer



System.nanoTime() returns the time in nanoseconds.


In order to get it in milliseconds, do System.nanoTime() / 1000000.


Here is an example how to calculate delta time properly.


long last_time = System.nanoTime();

while(running) {

long time = System.nanoTime();
int delta_time = (int) ((time - last_time) / 1000000);
last_time = time;
}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...