DEV Community

Cover image for Unity Time.deltaTime
Giorgi Eliozashvili
Giorgi Eliozashvili

Posted on

Unity Time.deltaTime

The interval in seconds from the last frame to the current one

Let's break it down a little:

You and your friend want to play a racing game, your PC is powerful and has 100 FPS in that said racing game, meanwhile, your friend has a slow PC, and it can only generate 10 FPS. What does this mean? This means that if a car is moving 1 meter per frame, your car will end up being way further, covering 100 meters per second because you have 100 FPS, while your friend's car will only cover 10 meters in a second because his PC is slower and generates only 10 FPS. !!! UNFAIR !!! You say, and you will be right. To make cars travel the same distance on both machines, you need Time.deltaTime. Now, how does it work? Time.deltaTime measures exactly how much time passed since the very last frame. On your PC, the time between frames is very short, 0.01 seconds, on your friend's PC, the time between frames is longer, 0.1 seconds. When you multiply your speed by Time.deltaTime Unity adjusts the movement to that time gap. So speaking easily, your computer does 100 tiny steps while your friend's computer does 10 bigger steps, but eventually you both move with the same speed.

How Time.deltaTime is calculated:

Time.deltaTime = Timestamp of Current Frame - Timestamp of Last Frame.

Explanation:

Frame 1 finished: Unity records time (e.g. 10.00 sec)
Frame 2 finished: Unity records time again (e.g. 10.03 sec)
Calculation: Unity subtracts 10.00 from 10.03 and gets 0.03, and assigns that value to Time.deltaTime (Time.deltaTime = 10.03 - 10.00)
The Update: **Unity **opens your Update() method and passes that 0.03 value into your movement calculation

Here is a small piece of code as an example of how to use Time.deltaTime:

void Update()
    {
        float x = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;

        transform.Translate(x, 0, 0);
    }

Enter fullscreen mode Exit fullscreen mode

What we do here is we declare a floating variable, and we assign X coordinates. To make our character move, we need to multiply X by moveSpeed and Time.deltaTime. So now our character moves on the X coordinate with the same speed on every machine.

Top comments (0)