# Converting Vector3D to Sphere Angles

This topic is 3990 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi All, I have a problem in that I want to extract the angles (phi and theta) from a specified 3D vector. For example, if I pass in the vector(1.0, 0.0, 0.0) then this would return (phi = 90.0 and theta = 90.0). Similarly if I pass in (0.0, 0.0, -1.0) then the angles would be 90.0 and 180.0 respectively. Any advices appreciated. MAMEman.

##### Share on other sites
Quote:
 Original post by mamemanI have a problem in that I want to extract the angles (phi and theta) from a specified 3D vector. For example, if I pass in the vector(1.0, 0.0, 0.0) then this would return (phi = 90.0 and theta = 90.0). Similarly if I pass in (0.0, 0.0, -1.0) then the angles would be 90.0 and 180.0 respectively.Any advices appreciated.
This is a lazy answer, but here's the corresponding conversion function from the CML:

/* Convert Cartesian coordinates to spherical coordinates in R3 */template < class VecT, typename Real > voidcartesian_to_spherical(const VecT& v, Real& radius, Real& theta, Real& phi,    size_t axis, SphericalType type,    Real tolerance = epsilon<Real>::placeholder()){    typedef Real value_type;    /* Checking */    detail::CheckVec3(v);    detail::CheckIndex3(axis);    size_t i, j, k;    cyclic_permutation(axis, i, j, k); // i=axis,j=(i+1)%3,k=(j+1)%3    value_type len = length(v[j],v[k]); // length(x,y)=sqrt(x*x+y*y)    theta = len < tolerance ? value_type(0) : std::atan2(v[k],v[j]);    radius = length(v, len);    if (radius < tolerance) {        phi = value_type(0);    } else {        phi = std::atan2(len,v);        if (type == latitude) {            phi = constants<value_type>::pi_over_2() - phi;        }    }}

I can't quite tell from your example what conventions you're using, but in the function shown above, the axis argument indicates which cardinal axis should be considered 'up' for the purpose of the conversion (0=x, 1=y, 2=z), and the type argument refers to whether phi should be considered to be latitude or colatitude.

##### Share on other sites
Just to highlight the math:

theta = atan(y/x) (use atan2(y,x) programmatically)
phi = acos(z/r)

(Where r is the length of your vector |v|.)

##### Share on other sites
@jyk. I always like those general solutions ;). Yes this has given me enough information to implement a solution for my particular problem. I can also make some assumptions in my case that reduces the maths to a few simple equations.

@wentworth. Yes you are correct. However my system is the one used by OGL i.e. z(coming out of the screen), y(up) and x(left). So in my case its theta = arctan(x/z) and phi = arcsin(r/rho) ;). Anyways thanks.

Cheers guys,

MAMEman.

1. 1
Rutin
23
2. 2
3. 3
JoeJ
20
4. 4
5. 5

• 28
• 40
• 23
• 13
• 13
• ### Forum Statistics

• Total Topics
631738
• Total Posts
3001950
×