Shortest distance along line within a certain distance of point

geometry

I have two points, $(x_0, y_0)$ and $(x_1, y_1)$. The point $(x_0, y_0)$ is on a line, which has angle $\theta$, relative to the X-axis.

Using these values, I want to be able to calculate the shortest distance, $d$, along the line (relative to $(x_0, y_0)$) which is less than 2 units away from $(x_1, y_1)$.

I suspect there may be something to do with slope and arctangent, but I can't make heads or tails of how I should attempt this (It's for a video game, in case that matters).

Sorry if this is a dupe, or if my math-speak is a bit too much programmer and a bit too little mathematician.

enter image description here

Best Answer

I'm assuming you want a programmatic approach instead of a purely analytic one, so I would attack this problem using standard transformations.

First, translate so $(x_0,y_0)$ lands on the origin - this corresponds to subtracting $(x_0,y_0)$ from each point.

Second, rotate by $-\theta$ so that the line $L$ lands on the $x$-axis - this corresponds to multiplying by the rotation matrix $$\begin{bmatrix} \cos \theta & \sin \theta\\-\sin \theta & \cos \theta\end{bmatrix}$$

Now, $(x_1, y_1)$ has been transformed to $(x_1^\prime , y_1^\prime)$, and we want to find the point on the $x$-axis within a distance of $2$ that has the smallest $x$ coordinate. Assuming $y_1^\prime \leq 2$:

If ${x^\prime_1}^2 + {y^\prime_1}^2 \leq 4$ then $(0,0)$ is the nearest point.

Otherwise:

If $x^\prime_1 > 0$, then $(x^\prime_1 - \sqrt{2^2 - {y_1^\prime}^2},0)$ is the nearest point.

If $x^\prime_1 < 0$, then $(x^\prime_1 + \sqrt{2^2 - {y_1^\prime}^2},0)$ is the nearest point.

Now, just reverse the transformations to find the coordinates you need.