TITLE: Shortest Distance Between Point and Line
QUESTION [0 upvotes]: I am working on a collision detection problem.
I wish to measure the distance from a point to a line segment.
i.e.
https://en.wikipedia.org/wiki/Distan..._by_two_points
I need to know the point on the line segment that the point (not on the line) is closest to.
i.e.
say the line segment is defined by
x1,y1 = 10,10
and
x2,y2 = 15,20
and there is a point at 16,16
how far is the shortest distance from the point to the line?
and where on the line is this shortest distance?
kind regards
W

REPLY [0 votes]: Let the line is given by two distinct points $A_1=(x_1,y_1)$ and $A_2=(x_2,y_2)$. Let the point you are studying be $B=(X,Y)$.
The points of the segment can be parametrised by $t\in[0,1]$ as
$$((1-t) x_1 + t x_2, (1-t) y_1 + t y_2),$$
and the square of the distance to them is therefore
$$ d(t) =  ((1-t) x_1 + t x_2 -X)^2 + ((1-t) y_1 + t y_2 -Y)^2 .$$
You need to minimise this function (it is a convex function, which is great) on a convex compact set $[0,1]$, which guarantees that the solution exists.
After expanding all terms in $d(t) $ you can rewrite it as
$$d(t) = a_2 t^2 + a_1 t + a_0, \quad t\in[0,1]$$
After that you have several cases to study, but nothing too complex. If you have troubles here, ask in comments.
Another approach would be to study the vectors $\vec x_1 = \vec{BA_1}$, $\vec x_2 = \vec{BA_2}$, and $\vec z = \vec{A_1A_2}$ and the triangle $A_1A_2B$. After loking carefully at the picture, you can get the following result.
The distance from the line to the point is $\frac{|\vec z \times \vec x_1|}{\|\vec z\|}$, where $\times$ stands for vector product. Let also $\cdot$ be a scalar product.
If $$(\vec x_1\cdot\vec z)(\vec x_2\cdot\vec z)<0,$$
then the distance you want is $\frac{|\vec z \times \vec x_1|}{\|\vec z\|}$
otherwise, the distance is $\min (\|\vec x_1\|,\|\vec x_2\|)$
{"set_name": "stack_exchange", "score": 0, "question_id": 1494296}