Sign in to follow this  

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

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

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 this post


Link to post
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 this post


Link to post
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)

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this