Delta Time : A difference over time

The simpliest way to animate the position of an object in real time, is to create a positionChange value, then to add it to the object’s position for one or more axis every frame.

    void Update()
    {
        float positionChange = 1;
        Vector3 change = Vector3.zero;
        change.y = positionChange;

        transform.position = transform.position + change;
    }

Result in Unity :

There is a problem : can you tell the speed of the object ? Is it the value of positionChange ? What is really a speed ?

The historical definition of speed is : the distance covered per unit of time.

v = d/t

where v is speed, d is distance in meter, and t is time in second.

So speed is how much distance in one second. Let’s write the definition of speed in code :

    void Update()
    {
        float distance = 2;
        float second = 1;
        float speed = distance / second;

        Vector3 velocity = Vector3.zero;
        velocity.y = speed;

        transform.position = transform.position + velocity;
    }

Result in Unity :

Unfortunately the result does not match what we expected. The vertical apparent speed of the object is nothing near the speed value we pluged in.

The framerate issue, explanation :

In real world, the speed is the distance covered for every second. But in Unity, time is sliced : the Update fonction is called once per frame, and there are dozen of frames each second. On top of that the framerate is not constant. That’s why the object goes up way too fast. In this problematic case here, the variable speed does not represent distance per second, but distance per frame.

Solution : the delta time.

The distance covered should not be for one complete second, but just for the elapsed time since the precedent frame.
The time difference between the last update and the actual update is obtained with :

Time.deltaTime;

The difference of something is usually labeled “delta” in mathematics.

The correct distance to add to the current position is found by scaling speed by delta-time.

    void Update()
    {
        float speed = 2;
        float positionDelta = speed * Time.deltaTime;

        Vector3 displacement = Vector3.zero;
        displacement.y = positionDelta;

        transform.position = transform.position + displacement;
    }

A shorter way to write this :

    void Update()
    {
        float speed = 2;
        transform.position += Vector3.up * speed * Time.deltaTime;
    }

In Unity the speed is now correct, and it is no more proportional to framerate :

Resume :
 
– Inconsistencies in frame rate create Inconsistencies in animation’s speed.
– DeltaTime allows a constant speed during real-time animations, independently of the frame rate.
– It is done by scaling speed by the deltatime each update.