You don't have to loop through all coordinates to check if two squares intersect.
Here's a simple solution which will work as long as the squares are not rotated.
Say that you represent a square by its top left corner coordinate and its side length. Let aX
and aY
represent the coordinates and aLen
the side length of square A
, and vice versa for square B
.
Then to check if square B
intersects with square A
evaluate this:
(aX < (bX + bLen) && (aX + aLen) > bX)
&& (aY < (bY - bLen) && (aY - aLen) > bY)
In other words, there are four possible scenarios and you check if either of square B
's corners are within the X-range of square A
and that either of square B
's corners are within the Y-range of square A
.
(Y)
^
| 1: 2:
| +--------+ +--------+
| | | | |
| | A +--|-----+ +-----+--+ A |
| | | | | | | | |
| +-----+--+ B | | B +--+-----+
| | | | |
| +--------+ +--------+
|
| 3: 4:
| +--------+ +--------+
| | | | |
| | B +--|-----+ +-----+--+ B |
| | | | | | | | |
| +-----+--+ A | | A +--+-----+
| | | | |
| +--------+ +--------+
|
+-------------------------------------------------> (X)
For more info see this answer of a similar question: Determine if two rectangles overlap each other?