2015-11-05 197 views
-1

我在基于中心的地图上有无限数量的点。它们应该排成一个多边形,所以它们的角度是360 /点数(http://prntscr.com/8z2w3z)。我有一个中心点,长度和方向,所以应该可以找到点的坐标。当我使用Bukkit创建一个Minecraft插件时,添加位置的唯一方法是添加它们的坐标,所以我不能简单地给他们一个方向。这是我希望的工作代码,但没有:获取正多边形的坐标

 float teamAngle = angle * teamNumber; 
     Location spawnPoint = mapCenter; 
     float relX = (float)Math.cos(Math.toRadians(teamAngle))*radius; 
     float relZ = (float)Math.sin(Math.toRadians(teamAngle))*radius; 
     spawnPoint.add(new Location(Bukkit.getWorld("world"), relX, 0, relZ, 0, 0)); 
  • teamAngle是每个点φ,所以连得4分,这将是0,90,180和270
  • radius是只是基于地图大小/ 2 * 0.8的浮点数。它可能不是最好的变量名

连得4分,我希望这样的事情(图宽100 =>半径40,中心在(0 | 0)):

  • 一(40 | 0)
  • B(0 | -40)
  • C(-40 | 040)
  • d(0 | 40)

编辑:事实上作为评论者表示, c奥多必须有点不同,我改变它以上

+1

“它没有工作”没有提供任何相关信息来帮助解决您的问题。 – Unihedron

+0

您的预期分数适用于45°,-45°,-135°,135°半径为56.5的角度。你应该得到的是(40,0),(0,40),(-40,0),(0,-40)。或者(28,28),( - 28,28)等'teamAngle = angle *(teamNumber + 0.5)'。 – LutzL

回答

1

你的想法背后计算坐标,据我所知是正确的。我只能猜测,你得到奇怪坐标的原因是因为你一遍又一遍地重复编辑同一个位置(尽管因为你只提供了一部分代码片段,我不能保证这是如此)。

Location spawnPoint = mapCenter不会创建新位置,它只会创建一个名为spawnPoint的引用,指向mapCenter

位置的add方法也不会返回新的Location实例。由于应该通过将x和y分量添加到中心位置来找到多边形的每个顶点,您必须复制或克隆mapCenter变量,以便不编辑/更改地图的原始中心。我假设您使用循环来创建/查找多边形的每个顶点位置,并且不会复制变量mapCenter,这将发生:

第1次迭代:角度为0º,将40添加到x坐标的spawnPoint(这改变mapCenter)和0spawnPoint的z坐标。假设地图的中心原本是0,0,0,坐标现在是40,0,0(这仍然是正确的)。

第二迭代:角为90°,加上0到X的spawnPoint坐标(再一次改变centerMap,这我们在最后一次迭代中已经编辑)的spawnPoint40协调与z。现在mapCenter的坐标是40,0,40,这是不正确的。我们应该将新组件添加到mapCenter的新副本中。

修复此使用Location spawnPoint = mapCenter.clone()。示例代码:

public static List<Location> getPolygonVertices(float radius, int edges, Location center) { 
    List<Location> vertices = new ArrayList<Location>(); 
    float angleDelta = 360/edges; // The change in angle measure we use each iteration 
    for (int i = 0; i < edges; i++) { // For each vertix we want to find 
     float angle = angleDelta * i; // Calculate the angle by multiplying the change (angleDelta) with the number of the edge 
     Location corner = center.clone(); // Clone the center of the map 
     corner.add(Math.cos(Math.toRadians(angle)) * radius, 0, Math.sin(Math.toRadians(angle)) * radius); // Add the x and z components to the copy 
     vertices.add(corner); 
    } 
    return vertices; 
} 

您可以使用此方法像这样:

List<Location> vertices = getPolygonVertices(40, 4, mapCenter); 

,它会返回到正确的位置([40 | 0],[0 | 40],[-40 | 0 ],[0 | -40])。

+0

你好,我正在使用'Location spawnPoint = mapCenter;'试图避免这个问题,但明白为什么它不起作用 –

+0

使用'Location spawnPoint = mapCenter'就是问题所在。您需要克隆该变量,否则您正在更改'mapCenter'本身,而不是将其用作原点的参考点。 –

+0

是的,它工作,谢谢。虽然我把花车改成了双打,因为它真的很精确 –