Libgdx中是否有办法验证Polygon和Circle之间的碰撞?
我看到了Intersector
类,但只发现了Circle和Rectangle的碰撞测试。那么其他任何多边形呢?
如果我需要手动完成,使用Libgdx最好的方法是什么?
答案 0 :(得分:11)
所以,我设法在Circle和Polygon之间创建了一个碰撞测试方法。至少,它适合我。
以下是代码:
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;
}
答案 1 :(得分:11)
可悲的是,我没有足够的声誉来评论,所以我将其作为另一个答案添加......
克里斯蒂亚诺的优秀答案适用于检查圆圈是否与多边形的一个线段重叠,但是它并不检查圆圈完全包含在多边形内部的更不寻常的情况,如果一个小的快速移动的圆与一个大的多边形相撞,就会发生这种情况。
我已经通过一些小改动将下面的克里斯蒂亚诺的代码翻译成了问题...
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);
}
答案 2 :(得分:0)
...并跟进Phil Anderson的优秀答案,这是我的版本,它只是避免每次检查都创建新的Vector2,而是重新使用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);
}
}