Geometry – Finding Perpendicular Distance from Point to Line in 3D

geometry

I have a Line going through points B and C; how do I find the perpendicular distance to A?

$$A= (4,2,1)$$
$$B= (1,0,1)$$
$$C = (1,2,0)$$

enter image description here

Best Answer

Intuitively, you want the distance between the point A and the point on the line BC that is closest to A. And the point on the line that you are looking for is exactly the projection of A on the line. The projection can be computed using the dot product (which is sometimes referred to as "projection product").

So you can compute the direction vector $\mathbb{d}$ of the line $BC$. This is the difference of $B$ and $C$, divided by their distance:

$$\mathbb{d} = (C-B) / ||C-B||$$

Then you can define a vector from $B$ to $A$:

$$\mathbb{v} = A - B$$

Computing the dot product between this vector and the direction vector will give you the the distance between $B$ and the projection of $A$ on $BC$:

$$ t = \mathbb{v} \cdot \mathbb{d}$$

The actual projection $P$ of $A$ on $BC$ is then given as

$$P = B + t \cdot \mathbb{d}$$

And finally, the distance that you have been looking for is

$$|| P - A||$$

Perpendicular

Of course, this could be written in a somewhat shorter form. It has the advantages of giving you exactly the closest point on the line (which may be a nice add-on to computing only the distance), and it can be implemented easily. Some pseudocode:

double computeDistance(vec3 A, vec3 B, vec3 C) {
    vec3 d = (C - B) / C.distance(B);
    vec3 v = A - B;
    double t = v.dot(d);
    vec3 P = B + t * d;
    return P.distance(A);
}
Related Question