0

我正在用 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

这是一种非常粗略的显示方式,但基本上我正在检查一个角是否与另一个对象相交。问题是,它不能同时考虑两个 axii。也就是说,即使一个对象高于另一个对象,也会发生 x 碰撞。

如果我检查两个轴上的碰撞,则无法判断它是水平碰撞还是垂直碰撞。或者也许有,我还没有弄清楚。

谁能指出我正确的方向?

4

1 回答 1

1

这是来自 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));
}
于 2013-10-11T00:16:30.937 回答