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

标签 java algorithm collision-detection

我有两个矩形,红色矩形(可以移动)和蓝色矩形。 两者都有:x, y, width, height。

当蓝色和红色矩形之间发生碰撞时,用 Java 等编程语言怎么说?

Example of collision

最佳答案

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

假设您有 Rect A 和 Rect B。通过反证法证明。四个条件中的任何一个都可以保证不存在重叠:

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

因此,Overlap 的充分条件正好相反(De Morgan)

不是条件 1 也不是条件 2 也不是条件 3 也不是条件 4 这相当于:

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

注 1:很明显,同样的原理可以扩展到任意数量的维度。 注 2:计算一个像素的重叠也应该相当明显,将边界上的 < 和/或 > 更改为 <= 或 >=。

如果您很难想象它的工作原理,我在 silentmatt.com/intersection.html 制作了一个示例页面,您可以在其中拖动矩形并查看比较结果。

关于java - java中两个矩形之间的碰撞检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31022269/

相关文章:

java - pm 命令给出段错误

java - 如何使用 Spring Security 实现登录页面,以便它与 Spring Web 流程一起工作?

c++ - 生成汉明距离 t 内的所有比特序列

box2d - 缩放 Box2D 圆形形状及其碰撞检测?

algorithm - 什么散列函数在对 n 个键进行散列时产生最大碰撞次数?

Java 9 在禁用调整大小后更改了 JFrame 的默认标题高度

performance - 数组中的随机整数。找出连续子集的最大和

c++ - if 条件的更好算法

iPhone SDK : Collision detection, 它必须是矩形吗?

java - Spring MVC 应用程序中的多个 ScriptTemplateViewResolvers