Search code examples
javagraphics2dlinerectangles

Calculate the points of a single line between two rectangles in Java


Assuming we have calculated the line segment between the centers of two rectangles that do not overlap.

...What's the easiest way in Java to recalculate the points of that line segment if we only consider the two points of intersection between the rectangles?

For example: Diagram of line intersection


Solution

  • This is essentially a math problem. There may be some methods that can help but that simply requires perusing the Math class and the java.awt.geom package.

    • first, find the center coordinates of each rectangle using origins and width and height.
    • then find the equation of the line between those coordinates y = mx + b. m is slope and b is y intercept. Here, x* and y* values are the centers of the rectangles. m = (y1-y2)/(x1-x2). b = y1 - m*x1 or you can also use y2 and x2.
    • then find the point of intersection of that line with each side. Again, you will need to use the origins and width and height to help figure this out. You may need to apply the equation just derived to determine if the line intersects a side or a top or bottom.
    • then using those points of intersection, find the line using the distance formula (think Pythagoras). Or Math.hypot()

    Note: Keep in mind that, as previously alluded to, the line may not always intersect on the sides. Depending on the relative locations of the rectangles, it could be tops and bottoms or the combination top and side or bottom and side. I recommend you do this on paper and cover all the possibilities before trying to code it.