How to find points of intersection of two rectangles?

521 Views Asked by At

Hi i need to find coordinates of where does two rectangles intersect. I have the coordinates of middle of each rectangle(square) and width/lenght of said rectangle. So for example i have square A and square B square A middle point is [2,2] and lenght is 2 square B middle point is [4,4] and lenght is 4

now i can calculate the coordinates of each square in left bottom, right bottom, left top and right top so lbA [1,1] rbA[3,1] ltA[1,3] , rtA[3,3] and lbB [2,2] rbB[6,2] ltB[2,6], rtB[6,6]

now when i draw this i see that they intersect in [3,2] and [2,3] but i need to find some kind of formula for this because i need to code this for any given squares. My attemp at this was for the program to get all coordinates of the square A and B and compare them and if there is a match i have coordinates of intersection but i feel like there has to be a easier way to do this.

1

There are 1 best solutions below

0
On

HINT for a general method.

Let the vertical sides of the first rectangle have equations $x=a$ and $x=b$. Let the vertical sides of the second rectangle have equations $x=A$ and $x=B$. For the horizontal sides let the equivalent equations be $y=c,y=d,y=C,y=D$.

There are a few possibilities. Perhaps the main one is where the rectangles intersect as in your example. This occurs when the rectangles intersect at a corner. For example, if $a<A<b<B$ and $c<C<d<D$ then the intersections occur at $(A,d)$ and $(b,C)$. In general, for possibilities like this, just use the pairs of 'inner' numbers.

The other main possibility is where both intersections occur on an edge of one rectangle. There is also the case where the rectangle intersect along a line of points. See if you can work out what is true about the numbers $a,b,A,B,c,d,C,D$ in such cases.