有没有办法知道libgdx中两个Rectangle之间的交叉矩形区域,比如c#http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle.intersect.aspx中的Rectangle?
我需要获得两个矩形之间的交叉矩形区域,但libgdx中的overlap方法只返回两个矩形相交的布尔值。 我已阅读过Intersector类,但它没有提供任何功能。
答案 0 :(得分: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;
}
答案 1 :(得分:5)
您可以使用Intersector类。
import com.badlogic.gdx.math.Intersector;
Intersector.intersectRectangles(rectangle1, rectangle2, intersection);
答案 2 :(得分:2)
我想在nEx软件的答案中添加一些细微的变化。即使您想将结果值存储在其中一个源矩形中,这个也会起作用:
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;
}
以下是usege的示例:
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
// ...
intersect(r1, r2, r1);