Java Noob
Java Noob

Reputation: 371

Intercept between rectangle and line drawn from center point

Consider the following diagram enter image description here

Given that A is the center point of the rectangle and the origin, and the coordinates for B, how do you find at what point Line AB intersects the rectangle? Thanks.

Upvotes: 1

Views: 534

Answers (2)

Lars
Lars

Reputation: 2485

I recommend to use JTS Topology Suite (https://github.com/locationtech/jts):

// create a rectangle from center point, width and height
public static LinearRing createRectangle(Coordinate center, double width, double height){
    Coordinate upperLeft = new Coordinate(center.x - (width/2), center.y + (height/2));
    Coordinate upperRight = new Coordinate(center.x + (width/2), center.y + (height/2));
    Coordinate lowerRight = new Coordinate(center.x + (width/2), center.y - (height/2));
    Coordinate lowerLeft = new Coordinate(center.x - (width/2), center.y - (height/2));
    LinearRing rectangle = new GeometryFactory().createLinearRing(new Coordinate[]{upperLeft, upperRight, lowerRight, lowerLeft, upperLeft});
    return rectangle;
}

// calculate intersection
public static Coordinate getIntersectionFromRectangleCenterAndCoordinate(LinearRing rectangle, Coordinate someCoord){
    // get your rectangle center coordinate (A)
    Coordinate rectangleCenter = rectangle.getCentroid().getCoordinate();
    // create line from center to someCoord (A - B)
    LineString lineFromCenterToSomeCoord = new GeometryFactory().createLineString(new Coordinate[]{rectangleCenter, someCoord});
    // calculate intersection
    Geometry intersectionGeom = rectangle.intersection(lineFromCenterToSomeCoord);
    // in your case just one intersection point...
    Coordinate intersectionCoordinate = intersectionGeom.getCoordinate();
    return intersectionCoordinate;
}

Upvotes: 0

MBo
MBo

Reputation: 80187

Intersection coordinates relative to center (A point):

dx = B.X - A.X
dy = B.Y - A.Y
if Width * Abs(dy) < Height * Abs(dx) then
   x = Sign(dx) * Width / 2
   y = dy * x / dx
else
   y = Sign(dy) * Height / 2
   x = dx * y / dy

Upvotes: 3

Related Questions