问题描述
我有两个矩形,红色矩形(可以移动)和蓝色矩形。
两者都有:x,y,width,height。
I have two rectangles, the red rectangle (can move) and the blue rectangle.Both have: x, y, width, height.
当蓝色和蓝色之间发生碰撞时,如何用Java等编程语言说出来红色矩形?
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)
假设您有Rect A和Rect B.证明是矛盾的。四个条件中的任何一个都保证不存在重叠:
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
因此,Overlap的充分条件恰恰相反(De Morgan)
Therefore, a sufficient condition for Overlap is the opposite (De Morgan)
不是Cond1而不是Cond2而不是Cond3而不是Cond4
这相当于:
Not Cond1 And Not Cond2 And Not Cond3 And Not Cond4This 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
注1:很明显,同样的原则可以扩展到任意数量的维度。
注2:计算一个像素的重叠也应该是相当明显的,改变<和/或那个边界上的>< =或a> =。
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 >=.
如果你很难想象它为什么会起作用,我做了一个示例页面在 silentmatt.com/intersection.html ,您可以在其中拖动矩形并查看比较。
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.
这篇关于java中两个矩形之间的碰撞检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!