I have two rectangles, the red rectangle (can move) and the blue rectangle. Both have: x, y, width, height.
How can I say in a programming language such as Java when there is a collision between the blue and the red rectangle?
if (RectA.X1 < RectB.X2 && RectA.X2 > RectB.X1 &&
RectA.Y1 < RectB.Y2 && RectA.Y2 > RectB.Y1)
Say you have Rect A, and Rect B. Proof is by contradiction. Any one of four conditions guarantees that no overlap can exist:
Cond1. If A's left edge is to the right of the B's right edge, - then A is Totally to right Of B
Cond2. If A's right edge is to the left of the B's left edge, - then A is Totally to left Of B
Cond3. If A's top edge is below B's bottom edge, - then A is Totally below B
Cond4. If A's bottom edge is above B's top edge, - then A is Totally above B
So condition for Non-Overlap is
Cond1 Or Cond2 Or Cond3 Or Cond4
Therefore, a sufficient condition for Overlap is the opposite (De Morgan)
Not Cond1 And Not Cond2 And Not Cond3 And Not Cond4 This is equivalent to:
A's Left Edge to left of B's right edge, and
A's right edge to right of B's left edge, and
A's top above B's bottom, and
A's bottom below B's Top
Note 1: It is fairly obvious this same principle can be extended to any number of dimensions. Note 2: It should also be fairly obvious to count overlaps of just one pixel, change the < and/or the > on that boundary to a <= or a >=.
If you are having a hard time visualizing why it works, I made an example page at silentmatt.com/intersection.html where you can drag rectangles around and see the comparisons.