I’m trying to implement two small function to convert Spherical coordinates to Cartesian and vice versa. But the output is different when the angle is higher than 180 (Math.PI).
const DEG2RAD = Math.PI / 180
const RAD2DEG = 180 / Math.PI
function sphericalToCartesian({ horizontal, vertical, radius }) {
const theta = horizontal * DEG2RAD
const phi = vertical * DEG2RAD
const vector = new THREE.Vector3()
vector.setFromSphericalCoords(radius, phi, theta)
return vector
}
function cartesianToSpherical({ x, y, z }) {
const sphere = new THREE.Spherical()
sphere.setFromCartesianCoords(x, y, z)
return {
vertical: sphere.phi * RAD2DEG,
horizontal: sphere.theta * RAD2DEG,
radius: sphere.radius,
}
}
Testing with 180 degrees:
const polar = sphericalToCartesian({ horizontal: 180, vertical: 180, radius: 10 })
console.log(cartesianToSpherical(polar)) // { vertical: 180, horizontal: 180, radius: 10 }
All good, but when trying 181 degrees this is the ouput:
{ vertical: 179.0000000000001, horizontal: 1.000000000000007, radius: 10 }
Ignoring the fact that JS is awful with Math operations, let’s asume that this is 179 and 1. I expected to be 181 and 181. Any idea on how to fix this?
Maybe I’m doing something wrong and I should not work with more than 180 (Math.PI) degrees?