Here's an idea. Instead of creating each rectangle with (x, y, width, height)
, instantiate them with (x1, y1, x2, y2)
, or at least have it interpret these values given the width and height.
That way, you can check which rectangles have a similar x
or y
value and make sure the corresponding rectangle has the same secondary value.
Example:
The rectangles you have given have the following values:
- Square 1: [0, 0, 8, 3]
- Square 3: [0, 4, 8, 6]
- Square 4: [9, 0, 10, 4]
First, we compare Square 1
to Square 3
(no collision):
- Compare the x values
- [0, 8] to [0, 8] These are exactly the same, so there's no crossover.
- Compare the y values
- [0, 4] to [3, 6] None of these numbers are similar, so they're not a factor
Next, we compare Square 3
to Square 4
(collision):
- Compare the x values
- [0, 8] to [9, 10] None of these numbers are similar, so they're not a factor
- Compare the y values
- [4, 6] to [0, 4] The rectangles have the number 4 in common, but 0 != 6, therefore, there is a collision
By know we know that a collision will occur, so the method will end, but lets evaluate Square 1
and Square 4
for some extra clarity.
- Compare the x values
- [0, 8] to [9, 10] None of these numbers are similar, so they're not a factor
- Compare the y values
- [0, 3] to [0, 4] The rectangles have the number 0 in common, but 3 != 4, therefore, there is a collision
Let me know if you need any extra details :)