I describe my spherical coordinates as following: (r, theta, phi) where theta [0, 2*PI) and phi [0, PI]
I noticed the problem with my function as I was accumulating values to my theta. Basically I get locked to a theta value of 89-91. If I convert the following spherical coordinate (3.0f, 91.0f, 0.0f) to cartesian coordinates I get (-2.99954, 0, 0.0523535). If I now convert THIS cartesian coordinate back to spherical coordinates I get (3, 89.0001, 0) which is clearly wrong. It then just continues in an endless cycle...goes up to 91 and goes back to 89 from there. To summarize the problem:
Spherical coord. (3.0f, 91.0f, 0.0f) -> Cartesian coord. (-2.99954, 0, 0.0523535)
Cartesian coord. (-2.99954, 0, 0.0523535) -> Spherical coord. (3, 89.0001, 0)
I've taken a look at both functions but I can't really figure out where the problem lies. Here is the code to both functions:
Spherical to cartesian
glm::vec3 Camera::sphericalToCartesian(glm::vec3 sphericalCoordinate)
{
GLfloat theta = degToRad(sphericalCoordinate.y);
GLfloat phi = degToRad(sphericalCoordinate.z);
glm::vec3 cartesianCoordinate(-cosf(phi)*sinf(theta), sinf(phi), -cosf(phi)*cos(theta));
return cartesianCoordinate * sphericalCoordinate.x;
}
Cartesian to spherical
glm::vec3 Camera::cartesianToSpherical(glm::vec3 cartesianCoordinate)
{
GLfloat r = (sqrt(pow(cartesianCoordinate.x, 2) + pow(cartesianCoordinate.y, 2) + pow(cartesianCoordinate.z, 2)));
GLfloat phi = (asinf(cartesianCoordinate.y/r)*180.0f)/PI;
//GLfloat radPhi = degToRad(phi); //Necessary?
GLfloat theta = (asinf(-cartesianCoordinate.x/(r*cosf(phi)))*180.0f)/PI;
glm::vec3 sphericalCoordinate(r, theta, phi);
return sphericalCoordinate;
}