[英]2D Vertical/Horizontal collision detection
我正在用Java编写2D平台器,但遇到了问题。 我有两个对象:都具有边界框,并且有四个坐标来表示框的角。
我的问题是我试图找到一种模拟碰撞的方法,但我似乎做不到。 我尝试在各处搜索,但是大多数站点只是展示OpenGL策略。
让我们这样表示边界框坐标:
TL:左上
TR:右上
BL:左下
BR:右下
这是我最初提出的测试碰撞的方式:
if(TL1 > TL2 && TL1 < TR2) //X-axis
//Collision happened, TL1 corner is inside of second object
else if(BL1 < TL2 && BL1 > BL2) //Y-axis
//Collision happened, BL1 corner is inside of second object
这是一种非常原始的显示方式,但是基本上我正在检查是否有一个角与另一个对象相交。 问题是,它并没有考虑到两个轴。 也就是说,即使一个物体位于另一物体上方,也会发生x碰撞。
如果我同时检查两个轴上的碰撞,则无法分辨是水平碰撞还是垂直碰撞。 也许有,但我还没有弄清楚。
谁能指出我正确的方向?
这是来自java.awt.Rectangle。
您应该能够对其进行修改以适合您的坐标。
/**
* Determines whether or not this <code>Rectangle</code> and the specified
* <code>Rectangle</code> intersect. Two rectangles intersect if
* their intersection is nonempty.
*
* @param r the specified <code>Rectangle</code>
* @return <code>true</code> if the specified <code>Rectangle</code>
* and this <code>Rectangle</code> intersect;
* <code>false</code> otherwise.
*/
public boolean intersects(Rectangle r) {
int tw = this.width;
int th = this.height;
int rw = r.width;
int rh = r.height;
if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {
return false;
}
int tx = this.x;
int ty = this.y;
int rx = r.x;
int ry = r.y;
rw += rx;
rh += ry;
tw += tx;
th += ty;
// overflow || intersect
return ((rw < rx || rw > tx) &&
(rh < ry || rh > ty) &&
(tw < tx || tw > rx) &&
(th < ty || th > ry));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.