There are two main ways to calculate distance in Unity.
- Use the Distance function to measure the distance between two points
- Use the Magnitude to measure the length of a single vector.
The Distance function
The Vector 3 Distance and Vector 2 Distance functions each accept two position values and will return a float thats representative of the distance between them.
public class CalculateDistance : MonoBehaviour
{
Vector3 targetPosition;
void Update()
{
float distanceToTarget = Vector3.Distance(transform.position, targetPosition);
}
}
This is useful when you want to measure the distance between two known points.
The Magnitude function
The Vector 3 Magnitude and Vector 2 Magnitude functions each accept a single vector value and will return the length of that vector.
public class CalculateDistance : MonoBehaviour
{
[SerializeField] float speed;
[SerializeField] Rigidbody rb;
void FixedUpdate()
{
speed = Vector3.Magnitude(rb.velocity);
}
}
This is useful when you want to measure the length of a known vector, such as the velocity of a rigidbody, for example, which can be useful for calculating speed.