有没有办法知道libgdx中两个矩形之间的相交矩形区域,就像c#http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle.intersect.aspx中的矩形一样?
我需要得到这两个矩形之间的相交矩形区域,但是libgdx中的重叠方法只返回布尔值,无论两个矩形是否相交。我读过跨部门类,但它没有提供任何功能。
事实上,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;
}
您可以使用跨部门类。
import com.badlogic.gdx.math.Intersector;
Intersector.intersectRectangles(rectangle1, rectangle2, intersection);
我想为nEx Software的答案添加一个微小的变化。即使您想将结果值存储在源矩形之一中,这个也可以工作:
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);