我正在使用 libgdx 编写一个小型太空游戏,飞船发射激光,我需要计算它何时(如果有的话)与多边形(小行星)相交。这样我就可以阻止激光穿过物体,并实际与它们发生碰撞。我的代码有时似乎可以工作,而在其他时候则完全失败。我不知道是什么导致它失败,我很确定这不是我的 poly 定义错误,因为有时它会在边缘工作,有时不会,没有一致性。
我检查了我的射线的痕迹(严格来说是一条线),它是正确的,所以不是那样的。这是代码,我将尝试解释我之后所做的事情。
//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;
}
}
}
我还应该从下面的图片中指出,我所说的激光是指明亮的核心,我没有打扰它的发光,这没有错,我只是还没做。
我希望这是足够的代码,如果还有什么我可以提供的,请询问;我很感激你能提供的任何帮助。
祝大家欢呼