public double distance(Pair <double, double> point) { // Solution found at http://www.codeguru.com/forum/printthread.php?t=194400 Pair <double, double> AC = makeVector(lower, point); Pair <double, double> BC = makeVector(upper, point); Pair <double, double> AB = makeVector(lower, upper); double r_numerator = LineSegment.dot(AC, AB); double r_denomenator = LineSegment.lengthSub(AB); double r = r_numerator / r_denomenator; Pair <double, double> P = new Multibrush.Pair <double, double>(lower.X + r * AB.X, lower.Y + r * AB.Y); double s = (AC.Y * AB.X - AC.X * AB.Y) / r_denomenator; double distanceLine = Math.Abs(s) * Math.Sqrt(r_denomenator); // If we lie within the partition the linesegment creates, then we just return the already calculated distance if ((r >= 0) && (r <= 1)) { return(distanceLine); } else { // If that is not the case, then we need to find out whether the point is closest to A or B double dist1 = LineSegment.length(AC); double dist2 = LineSegment.length(BC); if (dist1 < dist2) { return(dist1); } else { return(dist2); } } }
public double distance(Pair<double, double> point) { // Solution found at http://www.codeguru.com/forum/printthread.php?t=194400 Pair<double, double> AC = makeVector(lower, point); Pair<double, double> BC = makeVector(upper, point); Pair<double, double> AB = makeVector(lower, upper); double r_numerator = LineSegment.dot(AC, AB); double r_denomenator = LineSegment.lengthSub(AB); double r = r_numerator / r_denomenator; Pair<double, double> P = new Multibrush.Pair<double, double>(lower.X + r * AB.X, lower.Y + r * AB.Y); double s = (AC.Y * AB.X - AC.X * AB.Y) / r_denomenator; double distanceLine = Math.Abs(s) * Math.Sqrt(r_denomenator); // If we lie within the partition the linesegment creates, then we just return the already calculated distance if ( (r >= 0) && (r <= 1) ) { return distanceLine; } else { // If that is not the case, then we need to find out whether the point is closest to A or B double dist1 = LineSegment.length(AC); double dist2 = LineSegment.length(BC); if (dist1 < dist2) { return dist1; } else { return dist2; } } }