Functions for computing the distance between a Point and a Rectangle

This commit is contained in:
Tim Conkling
2011-12-16 12:35:25 -08:00
parent 060ff1b877
commit d2bebff736
2 changed files with 57 additions and 0 deletions
@@ -30,4 +30,39 @@ public class Rectangles
float y2 = Math.max(src1.maxY(), src2.maxY());
dst.setBounds(x1, y1, x2 - x1, y2 - y1);
}
/**
* Computes the Point on the rectangle that's closest to the given point, writing
the result int {@code out}
*/
public static Point closestInteriorPoint (IRectangle r, IPoint p, Point out)
{
out.set(MathUtil.clamp(p.x(), r.minX(), r.maxX()),
MathUtil.clamp(p.y(), r.minY(), r.maxY()));
return out;
}
/**
* Computes the Point on the rectangle that's closest to the given point
*/
public static Point closestInteriorPoint (IRectangle r, IPoint p) {
return closestInteriorPoint(r, p, new Point());
}
/**
* Returns the squared Euclidean distance between the given point and the nearest point on the
* given rectangle.
*/
public static float pointRectDistanceSq (IRectangle r, IPoint p) {
Point p2 = closestInteriorPoint(r, p);
return Points.distanceSq(p.x(), p.y(), p2.x, p2.y);
}
/**
* Returns the Euclidean distance between the given point and the nearest point on the
* given rectangle.
*/
public static float pointRectDistance (IRectangle r, IPoint p) {
return FloatMath.sqrt(pointRectDistanceSq(r, p));
}
}