Search code examples
libgdx

What is a Delta time in LIBGDX


What is a Delta time in LIBGDX? I read many posts regarding that. To my knowledge, Delta time is,

  • The time gap between previous and current frame
  • delta time will add upto 1 since its the computation of x frames per second ie.(1/x of the frames)
  • To make the speed constant for the game we use dt

    If we say 60 *dt then it will move 60 frames per second, no matter what the speed of the mobile(for instance) is.

    So, this is what I know about delta time but I am not getting a clear view about it because , be it for an update or render method we are passing the delta time but where in the code we are specifying to calculate for PER SECOND?

For example,

    public void update(float dt)
     {
       float distance +=2*dt;
     }

will this code move 2 frames per second? If so then what the below code will do?

    public void update(float dt)
    {
      ....
    }
    public void render(float delta)
    {
      update(delta);
    }

so, I need answers for,

  • what the above code is implying??
  • What's actually happening behind the code?
  • Why are we doing so?
  • where in this code we are specifying it must move x frames per second like the previous above example?

    I can understand the render method is passing the delta time to the update method but I need some clear view about it. Sorry if the question seems stupid but it's really hard to proceed without actually knowing what's happening .Any help would be great !!


Solution

  • Gdx.graphics.getDeltaTime() is the time between the start of the previous and the start of the current call to render(). It is also the value you get in your Screen#render() method. That's it. No black magic or something. It just takes the current time and subtracts the previous time from it. The unit of this value is seconds. Note that it does not add up to one.

    So if the previous time the method was called was at 6:51:30.0159512 pm and the current time it is called is at 6:51:30.0324858 pm then the difference is 0.0165346 seconds.

    Speed (velocity) is measured in "units" per second, for example meter per second or short: m/s. If your car travels at 360 m/s and the time elapsed is 0.0165346 s, then the distance you've traveled in that time is 0.0165346*360 s*m/s => 5.952456 m, so almost 6 meters.

    Note that this is basic physics, it is not specific to libGDX. If you find it hard to understand then you might want to read up on velocity.

    To answer your bottom questions, which I guess are about splitting your render method into an separate update method.

    • The code is not implying anything
    • There is nothing behind the code
    • Using well defined short methods is usually a good practice, read: separation of concerns
    • No clue what you mean by "frame" but the velocity is multiplied by the time to get the distance