我正在使用libgdx编写一个小型太空游戏,该船发射激光,我需要计算它何时(如果有的话)与聚合物(小行星)相交。这样我就可以阻止激光穿过物体,并实际与它们发生碰撞。我的代码似乎在某些时候有效,而在其他方面完全失败。我无法弄清楚是什么导致它失败,我很确定这不是我的多边形定义是错误的,因为有时它会在边缘工作,有时候不是,没有一致性。
我已经检查了我的光线的痕迹(严格来说是一条线)而且它是现货,所以不是那样。这是代码,我将尝试解释我之后所做的事情。
//Beam Collisions
//If the beam isn't being fired, return
if(!active) return;
//Storing all the points to be checked on the beam, I've checked the all seem accurate, and have draw a line between them and they match the laser.
List<Vector2> beamPoints = new ArrayList<Vector2>();
//Step allows me to reduce the number points I test when it finally works
int step = 1;
for(int n=0;n<maxHeight;n+=step){
//Rotation is the rotation of the ship. I add 90 to it so the angle of my vector is from the x-axis.
//shipX is the world coords of the ship. x is the relative start point of the laser to the ship.
//shipX refers to the centre of the ship, not the corner of the graphic.
beamPoints.add(
new Vector2(shipX+x+(float)(n*Math.cos(Math.toRadians(rotation+90))),
shipY+y+(float)(n*Math.sin(Math.toRadians(rotation+90)))));
}
//Here I cycle through the entities to test if they collide. Currently the only entities are asteroids.
for(Entity e : entities){
//Skip over the entity if it's outside the render range or it has no geometry.
if(!e.inRenderRange || e.getGeometry()==null) continue;
//A list to store all the vertices of that asteroids geometry.
List<Vector2> verts = new ArrayList<Vector2>();
for(Vector2 v : e.getGeometry()){
//Determining the x and y of the vertice to store. e.x is the asteroids world coords, I subtract the half the imageWidth because it's position is stored as the centre of the graphic.
//I then add the relative x and y of the vertex.
//I've turned off rotation for the asteroids, so that's not a problem.
float nx = (e.x-e.imageWidth/2)+v.x;
float ny = (e.y-e.imageHeight/2)+v.y;
verts.add(new Vector2(nx,ny));
}
//Testing each of the points on the beam to see if there are in the poly.
for(int j=0;j<beamPoints.size();j++){
//Using Intersector, a class in Libgdx, I can safely assume this is working fine.
if(Intersector.isPointInPolygon(verts, beamPoints.get(j))){
/Changing the height (should be labelled length) of the beam to be that at which it collides. Step is one, so doesn't matter for now.
height = j*step;
break;
}
}
}
我还应该从下面的图片中指出,通过激光我的意思是明亮的核心,我没有烦恼它的发光,这没有错,我还没有完成它。
我希望这是足够的代码,如果有什么我可以提供请问;我很乐意为你提供任何帮助。
干杯全部
答案 0 :(得分:2)
你真的在你的线路上产生大量离散点,然后用inPolygon
检查来测试每一点吗?这不是解决这个问题的好方法。
您的多边形由线段组成。你真正需要做的就是测试一个线段与你的光束相交,然后找到最近交点的实体。
关于线段交叉点的计算有很多信息。
这是来自SO的内容:How do you detect where two line segments intersect?