How can I get the distance between a point and a line segment following the direction given by a vector?

43 Views Asked by At

I am trying to code a function to get the distance from a point to a line segment in the direction specified by a vector. I found many examples on internet about how to get the minimum distance between a point and a line segment but none doing what I am asking here. Attached is an image that describes better what I am trying to do. Thanks in advance

1

There are 1 best solutions below

0
On BEST ANSWER

I am assuming your objects live in a plane, i.e. $\mathbb{R}^2$ (because otherwise It doesn't have to exist for arbitrary input, and even if it does, some rounding errors will be unavoidable, so let's stick to the simpler case).

Let $A$ and $B$ be the endpoints of the segment. Let $X$ be the point for which you are calculating the distance from the line segment and let $v$ be the vector of direction. Let $u$ be a vector perpendicular to $v$, i.e. if $v=(x,y)$, then $u=(y,-x)$ for example. Using the notation of scalar product, let $u$ be a vector such that $\langle u,v\rangle=0$. Calculate the "lengths along $u$" of $A,B$ and $X$: $L_A=\langle A,u\rangle$, $L_B=\langle B,u\rangle$, $L_X=\langle X,u\rangle$. The point $A+\frac{L_X-L_A}{L_B-L_A}(B-A)$ is what you're looking for.

This can be optimized a little bit:

Calculate $X'=X-A$ and $B'=B-A$. Now let $L_{X'}=\langle X',u\rangle$ and $L_{B'}=\langle B',u\rangle$. Then you are looking for $A+\frac{L_{X'}}{L_{B'}}B'$. This consists of 8 additions, 6 multiplications and 1 division. Not great, but good enough I hope.

Note, the inner-product is defined as $\langle(x,y),(z,t)\rangle=xz+yt$.