Sphere to Caresian Coordinates and vis versa

96 Views Asked by At

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.

1

There are 1 best solutions below

0
On

Use the atan2 function, as follows:

include <cmath>

float lat = std::atan2(cartCoord.position[Z],
                       std::hypot(cartCoord.position[X],
                                  cartCoord.position[Y]));
float lon = std::atan2(cartCoord.position[Y], cartCoord.position[X]);

atan2(y, x) = atan(y/x) except that the resulting angle is in the "right" quadrant.