libGdx 碰撞检测多边形



我最近开始学习LibGdx和Java,到目前为止进展顺利。 我遇到了碰撞检测问题。

我有两个精灵,可以表示为两个形状,一个多边形和一个圆,它们会在任何给定时刻碰撞/相交。一旦这两种形状发生碰撞,就会触发某些东西。

到目前为止,这就是我所做的。它有点有效,但不准确。这是在 Render(( 函数中调用的:

public boolean CollectPowerUp(PowerUps powerUp) {
if (powerUp.position.dst(position) < Constants.PLAYER_HEIGHT -3) {
Gdx.app.log("Collected PowerUp", "TRUE");
EnablePowerUp(powerUp);
return true;
}
return false;

我搜索过很多网站,大多数解决方案都包括其他软件,如2DCube或PhysicsEditor。是否可以仅使用 LibGdx 和 Java 来执行此交集?如果是这样,我应该调查什么?

谢谢

Intersector类具有许多可用于碰撞检测的静态方法。

如果您的多边形是矩形,则可以使用:

Intersector.overlaps(Circle c, Rectangle r)

Polygon polygon=new Polygon();
polygon.setVertices(new float[]{0,0,.......});
Circle circle=new Circle(x, y, radius);
float points[]=polygon.getTransformedVertices();
for (int i=0;i<points.length;i+=2){
if(circle.contains(points[i],points[i+1])){
System.out.println("Collide");
}
}       

编辑

上面的代码仅在多边形顶点在圆内时才检测碰撞,如果

  • 圆完全在多边形内
  • 的某些部分在多边形内,但顶点在圆外

为圆创建一个多边形,该多边形在视图中充当圆,在模型中充当多边形

float radius=100;
FloatArray floatArray=new FloatArray();
int accuracy=24;       // can be use 1 for complete circle
for (int angle=0;angle<360;angle += accuracy){
floatArray.add(radius * MathUtils.cosDeg(angle));
floatArray.add(radius * MathUtils.sinDeg(angle));
}
Polygon circle=new Polygon(floatArray.toArray()); // This is polygon whose vertices are on circumference of circle
float[] circularPoint=circle.getTransformedVertices();
for (int i=0;i<circularPoint.length;i+=2){
if(polygon.contains(circularPoint[i],circularPoint[i+1])){
System.out.println("Collide With circumference");
break;
}  
}

有一篇关于碰撞检测的好文章 www.gamedevelopment.blog 展示了如何检测大多数形状的碰撞。这是文章中所示的 Libgdx 圆、多边形碰撞检测方法。

public boolean contains (Polygon poly, Circle circ) {
final float[] vertices = poly.getTransformedVertices(); // get all points for this polygon (x and y)
final int numFloats = vertices.length; // get the amount of points(x and y)
// loop through each  point's x and y values
for (int i = 0; i < numFloats; i += 2) {
// get the first and second point(x and y of first vertice)
Vector2 start = new Vector2(vertices[i],vertices[i + 1]);
// get 3rd and 4th point (x and y of second vertice) (uses modulo so last point can use first point as end)
Vector2 end = new Vector2(vertices[(i + 2) % numFloats], vertices[(i + 3) % numFloats]);
// get the center of the circle
Vector2 center = new Vector2(circ.x, circ.y);
// get the square radius
float squareRadius = circ.radius * circ.radius;
// use square radius to check if the given line segment intersects the given circle.
return Intersector.intersectSegmentCircle (start, end, center, squareRadius);
}
}

扇间类中有许多有用的方法可用于冲突检测。

最新更新