Collision detection between two rectangles in Java

I have two rectangles, a red rectangle (movable) and a blue rectangle

When a collision occurs between blue and red rectangles, how to say it in programming languages such as Java?

Solution

if (RectA.X1 < RectB.X2 && RectA.X2 > RectB.X1 &&
if (RectA.X1 < RectB.X2 && RectA.X2 > RectB.X1 &&
    RectA.Y1 < RectB.Y2 && RectA.Y2 > RectB.Y1)

Suppose you have rect A and rect B. the proof is contradictory Any of the four conditions guarantees no overlap:

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, the sufficient condition of overlap is just the opposite (De Morgan)

Not cond1 instead of cond2 instead of cond3 instead of cond4, which 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: obviously, the same principle can be extended to any number of dimensions Note 2: calculating the overlap of a pixel should also be quite obvious. Change < and / or > on the boundary with < = or a > =

If it's hard for you to imagine how it works, I'm at silent att com/intersection. HTML, where you can drag a rectangle and view the comparison

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>