I want to convert from Cartesian to sphere coordinates and back
Here is my code
//the length (this is unit so could be dropped)
float p = cartCoord.getLength();
//x squared and y squared
float xsq = cartCoord.position[X]*cartCoord.position[X];
float ysq = cartCoord.position[Y]*cartCoord.position[Y];
//get the latitude and longitude of the sphere coords
float lat = acosf(cartCoord.position[X]/(sqrt(xsq+ysq)));
float lon = acosf(cartCoord.position[Z]/p);
//convert from spherical to Cartesian
float x = p * cosf(lat) * sinf(lon);
float y = p * sinf(lon) * sinf(lat);
float z = p * cosf(lon);
the values when converting back from spherical coordinates give the same absolute value as the original Cartesian coordinate but sometimes the negative values become positive and vis versa.
Could someone help me out where I am going wrong? As I have been searching high and low on the net for three days and cannot get my head around this.
Thanks, Nick.
Use the atan2 function, as follows:
atan2(y, x) = atan(y/x) except that the resulting angle is in the "right" quadrant.