Anyhoo, I need to figure out how to get the distance from a point to a sehment.
The segment is defined by two points. I already have done the part of the
function to get the distance if the segment is perfectly vertical.
Now, I know the distance to a line formula. I think what I need to do is
figure out a perpendicular from the point to the line containing the segment,
then test to see if that perpendicular passes through the segment. If the
perpendicular passes through the segment, I use the formula for distance to
aline. if the perpendicular does not pass through the segment, then I look for
distance to the endpoints, and see which is nearest.
Okay. How do I get an equation for a line from two points? I know, I should
know this, but my math final was last thursday, and I don't have a book
anymore. How do I have the computer handle it? Should I just store floats a,
b, and c for ax+by+c=0, or should I bother to make some sort of a line class,
or something esoteric like that? I am thinking just three floats.
Okay, now I magically have my line in the form of ax+by+c=0. How do I test to
see if the perpendicular to that line passes through the segment? This is
where I am pretty stumped. If I can do this, then I basically have distance to
a segment figured out... I just don't see how to limit a line to a segment.
Thanks for your time!
I have used a bit of vectors here and this may not be the most efficient.
Input is a line segment A(xa, ya) - B(xb, yb) and the point P(xp, yp).
double PointSegDistance(double xa, double ya, double xb, double yb,
double xp, double yp)
{
double dxap = xp - xa; // Vector AP
double dyap = yp - ya; //
double dxab = xb - xa; // Vector AB
double dyab = yb - ya; //
double ab2 = dxab*dxab + dyab*dyab; // Magnitude of AB
double t; // This will hold the parameter for the Point of projection of P
on AB
if (ab2 <= TOLERANCE) t=0.0; // A and B coincide
else t = (dxap*dxab + dyap*dyab) / ab2;
// Above equation maps to (AP dot normalized(AB)) / magnitude(AP dot
normalized(AB))
if (t<0.0) t = 0.0; // Projection is beyond A so nearest point is A
else if (t>1.0) t = 1.0; // Projection is beyond B so nearest point is B
double xf = x1 + t*dxab; // Projection point on Seg AB
double yf = y1 + t*dyab; //
double dxfp = xp - xf;
double dyfp = yp - yf;
return sqrt(dxfp*dxfp + dyfp*dyfp);
}