首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Libgdx -从Rectangle.overlap获取相交矩形(矩形)

Libgdx -从Rectangle.overlap获取相交矩形(矩形)
EN

Stack Overflow用户
提问于 2013-06-24 10:24:48
回答 3查看 3.9K关注 0票数 1

有没有办法像c# http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle.intersect.aspx中的矩形那样知道libgdx中两个矩形之间的相交矩形区域?

我需要得到这两个矩形之间的相交矩形面积,但libgdx中的overlap方法只返回布尔值,无论两个矩形是否相交。我读过Intersector类,但它没有提供任何功能。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-06-24 23:57:41

实际上,LibGDX没有内置此功能,因此我会这样做:

代码语言:javascript
复制
/** 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;
}
票数 8
EN

Stack Overflow用户

发布于 2014-05-31 22:33:52

您可以使用Intersector类。

代码语言:javascript
复制
import com.badlogic.gdx.math.Intersector;

Intersector.intersectRectangles(rectangle1, rectangle2, intersection);
票数 5
EN

Stack Overflow用户

发布于 2014-01-05 07:17:52

我想对nEx软件的答案做一点小小的改动。即使您希望将结果值存储在其中一个源矩形中,此方法也会起作用:

代码语言:javascript
复制
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;
}

下面是一个用法示例:

代码语言:javascript
复制
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();

// ...

intersect(r1, r2, r1);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17267221

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档