Search code examples
javascriptreactjsthree.jstrigonometry

Three.js, calculate sphere from polar coordinates


I am using three.js to calculate a sphere. I am using two for loops, one for theta and one for phi, and then I am transforming the polar coordinates to Cartesian coordinates. For every calculated point I add 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: Link


Solution

  • j must be in range [-90, 90] 9instead of [0, 260]. Notice that you are creating slices (360 °) from the South Pole to the North Pole (180 °).

    You must compute the sin(theta) and the cos(theta) and multiply both with cos(phi):

    let x = Math.sin(theta) * Math.cos(phi) * distance;
    let y = Math.sin(theta) * Math.sin(phi) * distance;

    let x = Math.cos(theta) * Math.cos(phi) * distance;
    let y = Math.sin(theta) * Math.cos(phi) * distance;
    

    Complete algorithm:

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

    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