Search code examples
javascriptthree.js3dspherical-coordinate

Moving point on sphere using spherical coordinates three js


I am trying to move a point for now randomly over the surface of a sphere. currently i am trying to do this by generating random spherical coordinates and then converting these to 3d locations with the function .setFromSphericalCoords()

This is what the code looks like that generates a new random spherical coordinate each frame:

element.kralenSpherical.phi += Math.random() * 2 -1;
if(element.kralenSpherical.phi <= 0 ) element.kralenSpherical.phi = 0;
else if(element.kralenSpherical.phi >= 180 ) element.kralenSpherical.phi = 180;
element.kralenSpherical.theta += Math.random() * 2 -1;
if(element.kralenSpherical.theta >= 360 ) element.kralenSpherical.theta = 0;
else if(element.kralenSpherical.theta <= 0) element.kralenSpherical.theta = 360;

element.kraal.position.copy(element.BaseLocation.clone().add(sphericalVector.setFromSphericalCoords(element.kralenSpherical.radius, element.kralenSpherical.phi, element.kralenSpherical.theta)));

this kinda works but currently my sphere point is not really moving over the sphere but rather jumping huge distances.

I think this has to do with what values i am supplying as phi and theta, but the problem is that i have no clue what the value range of phi and theta is.

If something is not clear let me know so i can clarify!


Solution

  • Not three.js but this should be easy to translate. As you well know, this is processing:

    
    
    void setup() {
      size(300, 300, P3D);  
      frameRate(300);
      background(0);
    }
    
    void draw() {
    
      lights();
      translate(width/2, height/2);
      stroke(255,255,0);
      noFill();
      //sphere(75);
    
      PVector v = noise_spherical_point(frameCount * 0.009, 75);
    
      translate(v.x, v.y, v.z);
      fill(255,0,0);
      noStroke();
      sphere(1);
    
    }
    
    
    PVector noise_spherical_point(float t, float rad) {
      float x = noise(t) * 2 -1;
      float y = noise(0, t)  * 2 -1;
      float z = noise(0, 0, t) * 2 -1;
      PVector v = new PVector(x, y, z);
      v = v.normalize();
      v.mult(rad);
      return v;
    }
    

    enter image description here