|
-
January 29th, 2010, 06:35 AM
#16
Re: Distance between point and line segment
This thing shows up on google if you search for this, and I really hate getting 15 search results that give you "Here's an algorithm that's got your solution in it somewhere! If you can find it! Maybe!" The most important problem here is that while this equation here ALMOST works:
http://mathworld.wolfram.com/images/...dEquation8.gif
It actually treats your segment as a line, which is useless. I found the answer buried in some obscure c code that does a variation on this technique: http://local.wasp.uwa.edu.au/~pbourk...tline/source.c - this contains a check that tells us if the point is within the line segment or not. Due to the similarity of the approaches i was able to integrate this into the previous equation for a function that, after almost 6 freaking hours of research, actually does exactly what we want it to do, under all circumstances.
Code:
float DistanceToPointSquared(float X, float Y)
{
float vx = x1-X, vy = y1-Y, ux = x2-x1, uy = y2-y1;
float length = ux*ux+uy*uy;
float det = (-vx*ux)+(-vy*uy); //if this is < 0 or > length then its outside the line segment
if(det<0 || det>length)
{
ux=x2-X;
uy=y2-Y;
return std::min<float>(vx*vx+vy*vy, ux*ux+uy*uy);
}
det = ux*vy-uy*vx;
return (det*det)/length;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|