1

i am trying to calculate the time passed in my libGDX application like this

 float timeSpent= 0;

public void render(){
  timeSpent = timeSpent + Gdx.graphics.getDeltaTime();

}

by the above code i feel like the time is almost passing double the normal rate

but if i get delta time directly from java's nano time method like this

float prevTime;
float timeSpent = 0;
public void show(){
   prevTime = System.nanoTime();
}
public void render(){
   float p = System.nanoTime(); 
   timeSpent  += (p-prevTime)/1000000000f;
   prevTime = p;
}

it seems to work fine, i know that libgdx also get delta time from subtracting nano time method.

i am not able to figure out what am i doing wrong in the first method.

thank you

kr15hna
  • 529
  • 1
  • 5
  • 12
  • What are you trying to calculate? Maybe try using `getRawDeltaTime()`. That calculates the time between the current and last frame without smoothing. If you want to calculate frame rate, there is a method for that `getFramesPerSecond()` – the-ginger-geek Nov 05 '15 at 07:16
  • @Neil thanks for the answer. i am trying to calculate the time passed from the application starting point . even using getRawDeltaTime() in place of getDeltaTime() doesn't work. i don't know why but timeSpent in the first method goes abnormally fast than it should – kr15hna Nov 05 '15 at 07:36
  • Time passed in seconds? – the-ginger-geek Nov 05 '15 at 07:41
  • @Neil yes time passed in seconds – kr15hna Nov 05 '15 at 09:44

1 Answers1

2

You can calculate the passed time from the start of your application by simply saving a date when it starts, and just subtract it from the current date. No need to accumulate the deltas in each frame.

You can further simplify the code by using TimeUtils:

// save at start
long start = TimeUtils.millis();

// query whenever you want
long diffInMillis = TimeUtils.timeSinceMillis(startTime);
kupsef
  • 3,357
  • 1
  • 21
  • 31
  • 1
    This is probably the best way to calculate passed time. Using float to count passed time may end up in floating point rounding errors especially in methods that are called very often like render() – TomGrill Games Nov 05 '15 at 09:28