圆形和多边形碰撞Libgdx(Circle and Polygon Collision with L

2019-07-21 06:57发布

是否有Libgdx一种方法来验证一个多边形与圆之间的冲突?

我看到了Intersector的类,但只有发现碰撞测试Circle和Rectangle。 怎么样任何其他多边形?

如果我需要做手工,什么是应该做的是使用Libgdx的最佳方式?

Answer 1:

所以,我设法创建一个圆和多边形之间的碰撞试验方法。 至少,它为我工作。

下面的代码:

public boolean overlaps(Polygon polygon, Circle circle) {
    float []vertices=polygon.getTransformedVertices();
    Vector2 center=new Vector2(circle.x, circle.y);
    float squareRadius=circle.radius*circle.radius;
    for (int i=0;i<vertices.length;i+=2){
        if (i==0){
            if (Intersector.intersectSegmentCircle(new Vector2(vertices[vertices.length-2], vertices[vertices.length-1]), new Vector2(vertices[i], vertices[i+1]), center, squareRadius))
                return true;
        } else {
            if (Intersector.intersectSegmentCircle(new Vector2(vertices[i-2], vertices[i-1]), new Vector2(vertices[i], vertices[i+1]), center, squareRadius))
                return true;
        }
    }
    return false;
}


Answer 2:

可悲的是我没有足够的信誉发表评论,所以我将以此作为另一种答案,而不是...

克里斯蒂亚诺的出色答卷工程检查圆圈重叠多边形的线段之一,但它不检查圆的更不寻常的情况下,多边形内部被完全包含,如果一个小的快速移动的圈相撞,这可能发生有一个大的多边形。

我repasted克里斯蒂亚诺的代码下面有小的改变来解决问题...

public static boolean overlaps(Polygon polygon, Circle circle) {
    float []vertices=polygon.getTransformedVertices();
    Vector2 center=new Vector2(circle.x, circle.y);
    float squareRadius=circle.radius*circle.radius;
    for (int i=0;i<vertices.length;i+=2){
        if (i==0){
            if (Intersector.intersectSegmentCircle(new Vector2(vertices[vertices.length - 2], vertices[vertices.length - 1]), new Vector2(vertices[i], vertices[i + 1]), center, squareRadius))
                return true;
        } else {
            if (Intersector.intersectSegmentCircle(new Vector2(vertices[i-2], vertices[i-1]), new Vector2(vertices[i], vertices[i+1]), center, squareRadius))
                return true;
        }
    }
    return polygon.contains(circle.x, circle.y);
}


Answer 3:

...并跟进菲尔·安德森的出色答卷,这里是我的版本,它只是避免了创造新的Vector2s每张支票,而是重新使用Vector2的静态实例。

public class PolygonUtil {

static final Vector2 center = new Vector2();
static final Vector2 vec1 = new Vector2();
static final Vector2 vec2 = new Vector2();

public static boolean overlaps(Polygon polygon, Circle circle) {
    float []vertices=polygon.getTransformedVertices();
    center.set(circle.x, circle.y);
    float squareRadius=circle.radius*circle.radius;
    for (int i=0;i<vertices.length;i+=2){
        if (i==0){
            if (Intersector.intersectSegmentCircle(vec1.set(vertices[vertices.length - 2], vertices[vertices.length - 1]),
                    vec2.set(vertices[i], vertices[i + 1]), center, squareRadius))
                return true;
        } else {
            if (Intersector.intersectSegmentCircle(vec1.set(vertices[i-2], vertices[i-1]), vec2.set(vertices[i], vertices[i+1]), center, squareRadius))
                return true;
        }
    }
    return polygon.contains(circle.x, circle.y);
}

}



文章来源: Circle and Polygon Collision with Libgdx