Hi everyone,
I am trying to convert the cartesian coordinates a PVector in 3D space, with coordinates (x, y, z) in spherical coordinates (so obtaining radius, theta and phi).
Below is the code I am testing, rarely it “works”, I guess there is something wrong so something is just inverted.
import peasy.*;
PeasyCam cam;
PVector p;
void setup() {
size(600, 600, P3D);
cam = new PeasyCam(this, 500);
// the vector with cartesian coordinates
p = PVector.random3D();
p.mult(100);
}
void draw() {
background(0);
// lines for the coordinate axis
stroke(100, 100, 255);
line(-width, 0, 0, width, 0, 0);
stroke(100, 255, 100);
line(0, 0, width, 0, 0, -width);
stroke(255, 100, 100);
line(0, -height, 0, 0, height, 0);
// the cube with cartesian coordinates
pushMatrix();
translate(p.x, p.y, p.z);
fill(255);
stroke(255, 100, 100);
noFill();
box(50);
popMatrix();
//conversion into spherical coordinates
float radius = sqrt(sq(p.x) + sq(p.y) + sq(p.z));
float theta = atan(p.y/p.x);
float phi = acos(p.z/radius);
float x = radius * cos(theta) * sin(phi);
float y = radius * sin(theta) * sin(phi);
float z = radius * cos(phi);
pushMatrix();
translate(x, y, z);
stroke(100, 255, 100);
noFill();
box(25);
popMatrix();
}
In the image, the red cube is the vector in cartesian coordinates, the green one the conversion in the code.
As a reference I am following the Spherical Coordinates page on Wolfram.
Where am I wrong?
Thank you in advance!