簡體   English   中英

2D垂直/水平碰撞檢測

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM