[英]libGdx collision detection Polygons
我最近开始学习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);
}
}
Intersector类中有许多有用的方法可用于碰撞检测。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.