2017-09-15 124 views
0

我想在一個球體上點一個點,然後將該點轉換爲相應的經度和緯度。我碰到這個問題,涉及到我做的幾乎一模一樣堆棧交換了後來Vector3到緯度經度

3D coordinates on a sphere to Latitude and Longitude

使用這個功能

public static LatLon FromVector3(Vector3 position, float sphereRadius) 
    { 
     float lat = (float)Math.Acos(position.Y/sphereRadius); //theta 
     float lon = (float)Math.Atan(position.X/position.Z); //phi 
     return new LatLon(lat, lon); 
    } 

但功能總是在範圍內的某處返回值對於lat爲0到3,對於經度爲-1到1。

我使用的程序是Unity,有誰知道爲什麼我可能會得到這些不正確的值?我將射線命中世界矢量和球體半徑作爲參數傳遞,球體以世界0,0,0爲中心。

非常感謝所有可能幫助您的人!

更新的代碼

public static Vector2 GetLatLonFromVector3 (Vector3 position, float sphereRadius){ 
     float lat = (float)Mathf.Acos(position.y/sphereRadius); //theta 
     float lon = (float)Mathf.Atan2(position.x, position.z); //phi 
     lat *= Mathf.Rad2Deg; 
     lon *= Mathf.Rad2Deg; 
     return new Vector2(lat, lon); 
    } 

我現在正在運行中的問題是該值沒有被正確地象限,他們在反映出來。在弧度

+0

如果Z分量很小,最好使用'Atan2(position.X,position.Z)'。 – meowgoesthedog

+0

當我切換到Atan2時,我得到完全不同的值,爲什麼? –

+0

因爲'Atan'不考慮你的「點」[X,Z]所在的象限;它也只覆蓋了180度的角度,而不是360度(這是phi的域) – meowgoesthedog

回答

2

反餘弦和反正切返回值,從-π(-3.1 ...)到π(3.1 ...)。爲了轉換爲度數,除以π並乘以180. Unity甚至有一個有用的常數,Mathf.Rad2Deg使其變得容易。

public static LatLon FromVector3(Vector3 position, float sphereRadius) 
{ 
    float lat = (float)Math.Acos(position.Y/sphereRadius); //theta 
    float lon = (float)Math.Atan(position.X/position.Z); //phi 
    return new LatLon(lat * Mathf.Rad2Deg, lon * Mathf.Rad2Deg); 
}