我最近开始学习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来执行此交集?如果是这样,我应该研究什么?
由于
答案 0 :(得分:2)
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;
}
}
答案 1 :(得分:2)
关于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);
}
}
Intersector类中有许多可用于碰撞检测的有用方法。