1

Is there any way to know the intersection Rectangle area between two Rectangles in libgdx like the Rectangle in c# http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle.intersect.aspx ?

I need to get the intersection rectangle area between that two rectangles but the overlap method in libgdx only return boolean value whether two rectangles are intersect or not. I have read Intersector class but it provides nothing to do that.

4

3 回答 3

8

Indeed, LibGDX does not have this functionality built in, so I would do something like this:

/** 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 回答
5

You can use the Intersector class.

import com.badlogic.gdx.math.Intersector;

Intersector.intersectRectangles(rectangle1, rectangle2, intersection);
于 2014-05-31T14:33:52.203 回答
2

I'd like to add a slight variation to the answer of nEx Software. This one will work even if you want to store the resulting value in one of the source rectangles:

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;
}

Here is an example usege:

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

// ...

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