My game uses a spherical terrain. As such, I want to be able to convert back and forth from spherical (latitude and longitude) coordinates, and Cartesian (xyz) coordinates. This will be convenient to use for other aspects later on. Anyways…
My math appears to be incorrect, and I cannot figure out why. I use the following class to do the conversions:
public static class CoordinateConverter {
public static float[] CartesianToSpherical(float x, float y, float z) {
float[] retVal = new float[2];
retVal[0] = Mathf.Acos(z / Terrain.RADIUS) * 180;
retVal[1] = Mathf.Atan2(y, x) * 180;
return retVal;
}
public static float[] CartesianToSpherical(Vector3 v) {
return CartesianToSpherical(v.x, v.y, v.z);
}
public static Vector3 SphericalToCartesian(float latitude, float longitude) {
float LAT = latitude * Mathf.PI/180;
float LON = longitude * Mathf.PI/180;
return new Vector3(
-Terrain.RADIUS * Mathf.Cos(LAT) * Mathf.Cos(LON),
Terrain.RADIUS * Mathf.Sin(LAT),
Terrain.RADIUS * Mathf.Cos(LAT) * Mathf.Sin(LON)
);
}
}
I test it with this code attached to my camera:
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100000f, Terrain.layerMask)) {
Gizmos.DrawRay(ray.origin, hit.point);
Gizmos.DrawSphere(hit.point, 100);
float[] latlon = CoordinateConverter.CartesianToSpherical(hit.point);
Vector3 test = CoordinateConverter.SphericalToCartesian(latlon[0], latlon[1]);
Gizmos.color = Color.yellow;
Gizmos.DrawSphere(test, 100);
}
The result is this for example:
The red sphere is where my ray hit. I pass that to my function to convert to latitude and longitude. I then pass the result back to the function to convert it back to Cartesian. I expect the yellow and red sphere to always be overlapping, but the yellow sphere moves around the planet wildly (although not randomly). For instance, if the red sphere moves up a bit, the yellow sphere moves left or right much faster. There is a certain point on the planet where they will intersect, but it is basically along the lines of “even a broken clock is correct twice a day”.
Anyone have any idea what is wrong with my calculations?