Algebraic way of checking if two rectangle overlap?

755 Views Asked by At

In a 2d plane, there exists a few different algorithms checking if two rectangles overlap.

I'm wondering if there exists an algebraic way of doing so? Of course, it would matter a lot on how to represent the rectangles, let's assume there are top left and bottom right coordinates for each rectangle given: $(TL_{11}, TL_{12}), (BR_{11}, BR_{12}), (TL_{21}, TL_{22}), (BR_{21}, BR_{22})$.

Can one construct an algebraic way to determine if two rectangles overlap?

1

There are 1 best solutions below

0
On

If the rectangles overlap you have two possible arrangements:

  1. They intersect in at least one edge
  2. One rectangle is contained in the other one

For 1. calculate the intersections of the lines defined by the coordinates and and vectors. If for two such lines the intersection parameters are between $0$ and $1$ you have such an intersection.

For 2. Note that this is exactly the case if all lines of the inner rectangule intersect the outer one outside of the inner one, but in two opposing places in the outer one.

So the algorithm would be: Suppose R1 is given by the nodes $a_1$, $a_2$, $a_3$, $a_4$ and let $v_1:=a_2-a_1,v_2=a_3-a_2,v_3=a_4-a_3,v_4=a_1-a_4$ and similarly R2 by $b_1,\ldots,b_4$ and $w_1,\ldots,w_4$.

For each pair of lines $l_i = a_i+tv_i$ and $r_j=b_j+hw_j$ calculate the intersection $t,h$. If for one such pair $0\leq t,h\leq 1$ they overlap, and if for all $i$ we have two $j$ with $0\leq h_j \leq 1$ and $\mathrm{sgn}(t_{j_1}) = -\mathrm{sgn}(t_{j_2})$ then R1 lies in R2.