Home > Software design >  Three js calculate sphere from polar coordinates
Three js calculate sphere from polar coordinates

Time:09-26

I am useing three.js an want to calculate a sphere. I am using two for loops one for theta and one for phi and then transforming the polar coordinates to Cartesian coordinates. For every calculated point I added a Point. The result is not a sphere.

This is the nested for loop:

const distance = 1000;
for (var i = 0; i < 360; i  = 10) {
  for (let j = 0; j < 360; j  = 10) {
    let theta = i * (Math.PI / 180);
    let phi = j * (Math.PI / 180);
    let x = Math.sin(theta) * Math.cos(phi) * distance;
    let y = Math.sin(theta) * Math.sin(phi) * distance;
    let z = distance * Math.sin(phi);
    const lightSphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
    lightSphere.position.set(x, y, z);
    scn.add(lightSphere);
  }
}

And here is the full code, including the result:

You create circles (slices) using Polar coordinate (distance, theta). The Cartesian coordinate can be get by:

xc = cos(theta) * distance
yc = sin(theta) * distance

Finally you do something similar for the sphere:

x = xc * cos(phi)
y = yc * cos(phi)
z = sin(phi) * distance
  • Related