java矩形碰撞检测,java中两个矩形之间的碰撞检测

这篇博客介绍了如何使用编程语言(如Java)判断两个矩形(红色和蓝色)是否发生碰撞。通过坐标轴上的边界条件比较,如红矩形左边缘是否在蓝矩形右边缘左侧,来确定是否存在重叠。博客还提供了矛盾条件的证明,并指出这种方法可以扩展到任意维度。此外,还提供了一个在线示例,用户可以通过拖动矩形观察碰撞检测的比较过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?

03qIb.png

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值