Time Delta is a core feature for any game development project. It allows objects to move around with a consistent speed and smooth movement regardless of which platform that you’re using (iOS, Android, PC, Mac, XBone etc)

So, a simple Unity scene…

…and a simple piece of code to go with it

using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading;
using UnityEngine;

public class SimpleMathExample01 : MonoBehaviour
{
public Vector3 m_position;
public Vector3 m_direction;
public Transform m_sphere;

// Start is called before the first frame update
void Start()
{
m_position = Vector3.zero;
m_direction = new Vector3(10.0f, 0.0f, 0.0f);
}

// Update is called once per frame
void Update()
{
float delta = Time.deltaTime;
m_position += m_direction * delta;
m_sphere.position = m_position;
}
}

In the above code, we have a position, a direction and an object that we’re moving.

The Start function sets the position to 0, 0, 0 (the middle of the scene) and the direction to 10.0f, 0.0f, 0.0f. This means that we’re going to move 10 meters per second in the X direction, none in the Y and none in the Z

Every time the Update is called, we add the direction to the position, BUT we multiply by the Time.deltaTime value. This is a float value that tells us what fraction of a second has passed since the last update. If one second has passed (for example) then the value would be 1.0. If half a second had passed the the value would be 0.5.

We use this Time Delta as a multiplier for the direction vector which makes the direction vector work as a distance to move ‘per second’ instead of just a distance to move per update

If we don’t apply the Time Delta then the position will update by the direction vector every time the Update is called and this will result in very fast movement that isn’t consistent across all types and speeds of device.

For a quick overview, take a look at this YouTube video here


Discover more from

Subscribe to get the latest posts sent to your email.

Leave a comment

Trending