Sunday, November 6, 2011

Using Vector Mathematics, finding distance between points

Finding the distance between points is fairly simple, especially if you're familiar with the Pythagorean Theorem. The Pythagorean Theorem is the formula for finding the length of the hypotenuse of a triangle, which is essentially from finding the distance between two points in 2D space.

Pythagorean Theorem in its simplest form:
a² + b² = c²

If you've taken geometry then you likely know about a 3-4-5 triangle. Which is a commonly known fact that a right triangle can legally have sides with lengths of 3, 4, and 5. Using the Pythagorean Theorem we can prove this:
3² + 4² = 5², or 9 + 16 = 25, and √25 = 5.

So how is this related to finding the distance between two vectors? Let's think of the formula in a different way:
x² + y² = length², so with a 2D vector of (3, 4), that vector will have squared length of 25. Finding the length of the vector (3, 4) is the same as distance between (0, 0) and (3, 4), so you now essentially know how to find the distance between two points. If one of points is not (0, 0) you just use vector subtraction to get the difference between the two vectors, and get the length of that. For example, if we have two points, (1, 4) and (3, 5), the difference between them is ( 3-1, 5-4 ), which comes to (2, 1), and the length of (2, 1) is √(2² + 1²) or √5.


As you can see, finding the length of a 2D vector is essentially using the Pythagorean Theorem. A 3D version of this is just as you might imagine:
x² + y² + z² = length², which simplifies to √(x² + y² + z²)


So here's the function to get the length of a vector:

float GetLength( const Vector3& inVect )
{
    return sqrtf( inVect.x * inVect.x
                + inVect.y * inVect.y
                + inVect.z * inVect.z );
}

And you'll most likely want this function as part of the Vector class itself, here's a version for that:

inline float Vector3::Length() const
{
    return sqrtf( x*x + y*y + z*z );
}

And a nice helper function for finding the distance between two points, using the GetLength() function we already made above:

inline float DistanceBetweenTwoPoints( const Vector3& first, 
                                       const  Vector3& second )
{
    const  Vector3 differenceVector = second - first;
    return GetLength(differenceVector);
}

No comments:

Post a Comment