# quick math question. ...

This topic is 5015 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Given a test point P, and a line segment AB, how do you determine the point on AB that is closest to P? thanks

##### Share on other sites
The position of the closest point P2 is there where a line from P to P2 is perpendicular (90 degree angle) to line AB.
So knowing the position of the points and the angle, it's a matter of basic trigonometry.

##### Share on other sites
The line is given by the equation:

x = A + t * (B - A) / |B - A|

The dot product '.' can be used to project a vector onto another:

u.v = |u|*|v|*cos(alpha)
=>
|v|*cos(alpha) = u.v / |u|

So use it in the line equation:

u = B - A
v = P - A
t = u.v / |u|

And you get

x = A + (B-A) * (B-A).(P-A) / |B-A|²

##### Share on other sites
Here's another method. Convert the line segment AB into origin/direction form, like this:

Vector O = A;
Vector D = B-A;

Now find the parametric projection of P onto AB:

float t = Dot(P-O, D)/Dot(D, D);

If you want the closest point on the segment rather than on the infinite line, clamp t to [0, 1]:

if (t < 0.0f) t = 0.0f; // Or return O
if (t > 1.0f) t = 1.0f; // Or return O+D

Now use t to find the point on AB closest to P:

return O+tD;

[Edit: same as what nmi said.]

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 10
• 11
• 13
• 9
• 9
• ### Forum Statistics

• Total Topics
634082
• Total Posts
3015401
×