2015-11-05 142 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

是的,它工作,謝謝。雖然我把花車改成了雙打,因爲它真的很精確 –