Merge pull request #7 from tconkling/master
Rectangles.pointRectDistance and associated unit test
This commit is contained in:
@@ -30,4 +30,39 @@ public class Rectangles
|
|||||||
float y2 = Math.max(src1.maxY(), src2.maxY());
|
float y2 = Math.max(src1.maxY(), src2.maxY());
|
||||||
dst.setBounds(x1, y1, x2 - x1, y2 - y1);
|
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));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
//
|
||||||
|
// Pythagoras - a collection of geometry classes
|
||||||
|
// http://github.com/samskivert/pythagoras
|
||||||
|
|
||||||
|
package pythagoras.f;
|
||||||
|
|
||||||
|
import org.junit.*;
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class RectangleTest
|
||||||
|
{
|
||||||
|
@Test public void testPointRectDistance () {
|
||||||
|
testPointRectDistance(0, new Rectangle(0, 0, 10, 10), new Point(0, 0)); // edge
|
||||||
|
testPointRectDistance(0, new Rectangle(0, 0, 10, 10), new Point(5, 5)); // interior
|
||||||
|
testPointRectDistance(5, new Rectangle(0, 0, 10, 10), new Point(5, 15)); // exterior
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void testPointRectDistance (float expected, IRectangle r, Point p) {
|
||||||
|
assertEquals(expected, Rectangles.pointRectDistance(r, p), MathUtil.EPSILON);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user