Distance From Point To Line
From CGAFaq
The distance between a point C and a line L is the distance from C to the nearest point N on L. The nearest point is given by the fact that the line between N and C must be perpendicular to L. Thus:
Let the line L be parametrized by
L(t) = P + tD
where
P is a point on the line
D is a vector denoting the direction of the line
The condition for perpendicularity is
dot(N − C,D) = 0
Using the properties of the dot product yields
dot(L(s) − C,D) = 0
dot(P + sD − C,D) = 0
dot(sD,D) + dot(P − C,D) = 0
s * dot(D,D) + dot(P − C,D) = 0
s = − dot(P − C,D) / dot(D,D)
s = dot(C − P,D) / dot(D,D)
The division can be avoided by choosing D a unit vector.
The distance between C and L is then given by:
distance(C,L) = | | L(s) − C | |