1

c# http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle.intersect.aspxの Rectangle のように、libgdx の 2 つの Rectangle 間の交差 Rectangle 領域を知る方法はありますか?

その2つの長方形の間の交差長方形領域を取得する必要がありますが、libgdxのオーバーラップメソッドは、2つの長方形が交差しているかどうかに関係なくブール値のみを返します。Intersector クラスを読みましたが、何も提供していません。

4

3 に答える 3

8

実際、LibGDX にはこの機能が組み込まれていないため、次のようにします。

/** Determines whether the supplied rectangles intersect and, if they do,
 *  sets the supplied {@code intersection} rectangle to the area of overlap.
 * 
 * @return whether the rectangles intersect
 */
static public boolean intersect(Rectangle rectangle1, Rectangle rectangle2, Rectangle intersection) {
    if (rectangle1.overlaps(rectangle2)) {
        intersection.x = Math.max(rectangle1.x, rectangle2.x);
        intersection.width = Math.min(rectangle1.x + rectangle1.width, rectangle2.x + rectangle2.width) - intersection.x;
        intersection.y = Math.max(rectangle1.y, rectangle2.y);
        intersection.height = Math.min(rectangle1.y + rectangle1.height, rectangle2.y + rectangle2.height) - intersection.y;
        return true;
    }
    return false;
}
于 2013-06-24T15:57:41.400 に答える
2

nEx Software の回答に少しバリエーションを加えたいと思います。これは、結果の値をソース長方形の 1 つに格納したい場合でも機能します。

public static boolean intersect(Rectangle r1, Rectangle r2, Rectangle intersection) {
    if (!r1.overlaps(r2)) {
        return false;
    }

    float x = Math.max(r1.x, r2.x);
    float y = Math.max(r1.y, r2.y);
    float width = Math.min(r1.x + r1.width, r2.x + r2.width) - x;
    float height = Math.min(r1.y + r1.height, r2.y + r2.height) - y;
    intersection.set(x, y, width, height);

    return true;
}

使用例を次に示します。

Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();

// ...

intersect(r1, r2, r1);
于 2014-01-04T23:17:52.327 に答える