How can I check if two squares intersect?

4.2k Views Asked by At

square1 = (47,15) (51,15) (51,19) (47,19)

square2 = (19,0) (-27,46) (19,92) (65,46)

These two squares may not be parallel to X axis or Y axis.

These two squares do not intersect, but how can I find it mathematically from those points?

1

There are 1 best solutions below

1
On

If the squares are axis aligned like your example you can just check whether any corner of one square is within the other one. To check if $(19,0)$ is in the first square you just check if $19$ is between $47$ and $51$ and whether $0$ is between $15$ and $19$. You need both checks to pass, but here they both fail. Try the other three corners, then swap the squares and you are done.

If the sides of the squares are not parallel it is necessary to look for intersections between the sides. You can have two squares overlap without any corner being in the other-think of an eight pointed star. Compute the slope of each side as $m=\frac {y_2-y_1}{x_2-x_1}$ Taking the sides in pairs, one from each square, find the intersection point of the lines they are on. See if that point is on the side of both squares. If so, the squares intersect. You have to watch out for division by zero here.