When to use Time.deltaTime?

I have an idea of what Time.deltaTime is and what it is used for, but I’m not sure if I need to use it in my case. I am moving the position of Transfrom using Vector3.SmoothDamp:

transform.position = Vector3.SmoothDamp(transform.position, targetPosition, velocity, 0.2);

targetPosition is a Vector 3 value for touch position on the screen. Thus the object is following the touch position. Should I multiply values of x, y and z by Time.deltaTime for targetPosition?

Time.deltaTime should be used, when you want movement or any other constant variable change, to be the same speed, no matter the framerate.

How does it work?

DeltaTime is the time between the last and current frame. If the game’s running at 10 fps, it’s 0.1 (1 / fps), if the game’s running at 20 fps, it’s 0.05.

How does this help?

Lets take:

transform.position += Vector3.right * 5;

This addition doesn’t have deltaTime in it. This means, if the game’s at 30 fps, it’ll move 150 world units a second, but if the fps is 60, it’ll be 300 world units.

The second example includes deltaTime:

transform.position += Vector3.right * 5 * Time.deltaTime;

In this case, if the game’s fps is 30, it’ll add 5 * 0.033 each frame, resulting in 5 units/second. The second case would be 60 fps, so the code would add 5 * 0.0166 units per frame to the x position, with the same result, 5 units/second.

All this can be turned into a general equation:

When:

x += speed * (1 / fps) = speed / fps

Then, to get the result for one second, we need to multiply the right side by fps, which results in:

x[metres] = speed[m/s] * t~~;~~

–David–

You must always use Time.deltaTime when moving objects over time, either by supplying it yourself or by making use of functions like SmoothDamp that use Time.deltaTime by default (hardly any functions do that though). But you must never use Time.deltaTime for input that’s already framerate-independent, such as mouse movement, since in that case using Time.deltaTime will do the opposite of what you intend.

If you’re ever unsure you can always toggle vsync on and off and observe any potential speed differences. If the game’s already running close to the monitor refresh rate anyway, then make use of Application.targetFrameRate instead.

You should use Time.deltaTime for any framerate dependant thing. If you were just setting your object position to touch position, then there would be no point using Time.deltaTime since no matter the framerate, your object would still be at touch pos. But since your trying to smoothly go to that position, then yes : you should use Time.deltaTime to make sure your object moves equally fast whether your game is running slow or fast. :wink:

There is no need to pass deltaTime to that function though, it already has deltaTime passed by default !

Hope it helps !