How to calculate speed in Unity

In by John FrenchPublished Updated

There are two main methods for calculating speed in Unity, depending on whether or not the object is moving using physics, the Rigidbody Method and the Position Method.

The Rigidbody Method

If the object has a Rigidbody component, meaning that it’s being moved under physics simulation, then the speed of its movement can be used by measuring the length of the object’s linear velocity.

public class CalculateSpeed : MonoBehaviour
{
    [SerializeField] float speed;
    [SerializeField] Rigidbody rb;

    void FixedUpdate()
    {
        speed = Vector3.Magnitude(rb.velocity);
    }
}

The Position Method

It’s possible to measure an object’s speed by calculating the distance between its current position and its last position using the Vector 3 Distance function. This provides the distance that has been travelled since the last frame, which can divided by Delta Time to calculate the movement in units per second.

public class CalculateSpeed : MonoBehaviour
{
    [SerializeField] float speed;
    Vector3 lastPosition;

    void Update()
    {
        float distanceTravelled = Vector3.Distance(lastPosition, transform.position);
        speed = distanceTravelled / Time.deltaTime;
        lastPosition = transform.position;
    }
}

When measuring physics-based movement using the position method, it’s important to calculate the movement in Fixed Update, not Update.