Mastering Unity's Time.deltaTime
Unity 3D Essentials
In any 3D game you’re likely to encounter a situation where you want to do a time-based feature.
For example, moving an object or character X units per second. Using Time.deltaTime
is going to help avoid frame-rate dependence.
What is Time.deltaTime?
- The time in seconds between the last frame and the current frame
How often is Update() called?
- Update is called every frame
Why use Time.deltaTime?
- In a nutshell, it allows us to go from:
- “Do [Some-time-based-action] per frame” to
- “Do [Some-time-based-action] per second”
Example: Move an object 2 meters per second
- Note: it is 2 meters per second
- It it NOT 2 meters per frame
Frame-rate Dependent movement (incorrect)
private float m_MetersPerFrame = 2;
void Update()
{
// move forward metersPerFrame meters PER FRAME
transform.Translate(Vector3.forward * metersPerFrame);
}
- Since the above is frame-rate dependent, the following will occur at the respective FPS:
- Moving 2 meters/frame:
- 60FPS => 2 * 60 = 120 meters covered in 1 second
- 30FPS => 2 * 30 = 60 meters covered in 1 second
- Moving 2 meters/frame:
- For the same time (1 second) the object’s distance covered will be different – this is bad and will produce unexpected behaviour.
Frame-rate Independence (correct)
Time.deltaTime
helps us prevent frame-rate dependence on any time-based actions
private float m_MetersPerSecond = 2;
void Update()
{
// move forward m_MetersPerSecond meters PER SECOND
transform.Translate(Vector3.forward * m_MetersPerSecond * Time.deltaTime);
}
- Since we’re multiplying by the time taken since the last frame (a variable value), this allows us to scale our movement steps to ensure the same distance is moved per second
- The following will occur at the respective FPS:
- Moving 2 meters/second:
- 60FPS => 2 60 1/60 = 2 meters covered in 1 second
- 30FPS => 2 30 1/30 = 2 meters covered in 1 second
- Moving 2 meters/second:
Therefore, whenever you’re developing a time-based feature, ensure you’re using Time.deltaTime.