In this lesson, you will learn how to mathematically determine the distance between two objects and calculate the exact direction required to move one toward the other.
Understanding Vectors
In Unity, a Vector3 represents a point in 3D space or a direction with a specific length. When you want to move a character toward a target, you need two pieces of information: How far away is the target? (Magnitude) and Which way should I face to get there? (Direction).
Calculating Distance (Magnitude)
To find the distance between two objects, you first find the vector that points from one to the other by subtracting their positions:
Vector3 difference = target.position - player.position;
The "length" of this difference vector is the distance between them. In Unity, we use the .magnitude property to get this value.
Calculating Direction (Normalization)
If you try to use the difference vector to move your player, the player might move too fast if the target is far away, or too slow if it’s close. To fix this, we need a "normalized" vector. A normalized vector keeps the same direction but scales its length to exactly 1. This is called a unit vector.
You can calculate this using the .normalized property:
Vector3 heading = target.position - player.position;
float distance = heading.magnitude;
Vector3 direction = heading.normalized;
With this direction (a vector with a length of 1), you can now multiply it by a speed value to ensure your character moves at a consistent rate regardless of how far the target is located.
Think of it like a compass: the direction tells you "North-East," and the magnitude tells you "it is 50 meters away." By combining these, your code can navigate any object toward another with precision.
Key Takeaway: Use .magnitude to measure the distance between two points and .normalized to create a direction vector with a length of 1 for consistent movement logic.