# an efficient way to get distance from point to segment in 2D

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

## Recommended Posts

hey every one , I would like to ask if there any formula to get distance from point A, to plane/segment B-C.

Edited by MaorNr

##### Share on other sites

I'm not sure if you want point-to-line-segment or point-to-infinite-line, but here's code for the former:

//given seg defined as points p0,p1, return distance to query point qp
float getDistanceToSeg(float2 p0, float2 p1, float2 qp)
{
float2 p0p1 = p1 - p0;
float2 p0qp = qp - p0;

float len2 = dot(p0p1, p0p1);

//t is a number in (0,1) describing the closest point on the lineseg as a blend of endpoints..
//this one line is hiding a lot of intermediate calcs/simplification, maybe it's too tricky.. I don't have time to remember the full process!
float t = max(0, min(len2, dot(p0p1, p0qp))) / len2;

float2 cp = p0 + t*p0p1;//this is the closest point on the seg in worldspace (or whatever space we're in)

return len(cp - qp);

}


##### Share on other sites

If you express a 3d plane as

a*x+b*y+c*z+d=0

where [a,b,c] vector is a unit vector normal to the plane and d the disposion value.

Then distance of point K=[k,m,l] from that plane is k*a+m*b+l*c+d=D , where D is the signed distance from plane.

The real equation is actualy (k*a+m*b+l*c+d)/sqrt(a*a+b*b+c*c), but if the normal vector [a,b,c] in the plane equation is a unit vector, then you don't need to devide by its length.

You can find out planes formed by arbitrary 2 3d points. subtract them, C=A-B, and the C formed vector is normal to plane that contains either point A or point B. Normalize C vector, and then you can find out value d for both of those planes, for the plane containing A vector the disposion is -d=dot(A,C), and for the plane containig B the disposision is -d=dot(B,C).

##### Share on other sites
What is a "plane/segment"?

##### Share on other sites

What is a "plane/segment"?

Yeah there's a pretty big difference between a plane and segment. Plane would require a dot product and subtraction (or addition), while a segment would require testing voronoi regions.

##### Share on other sites

a segment would require testing voronoi regions.

It's not super-important, but I just wanted to point out that you can actually find point-to-lineseg distance without explicitly testing voronoi regions -- you just project the point onto the line containing the lineseg, then clamp to the lineseg ends. (see my above code)

1. 1
2. 2
3. 3
4. 4
frob
13
5. 5

• 16
• 13
• 20
• 12
• 19
• ### Forum Statistics

• Total Topics
632170
• Total Posts
3004547

×