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

Started by
4 comments, last by raigan 9 years, 5 months ago

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

Advertisement

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);

}

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).

What is a "plane/segment"?

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.


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)

This topic is closed to new replies.

Advertisement