Skip to content

Instantly share code, notes, and snippets.

@handeyeco
Created August 29, 2017 19:21
Show Gist options
  • Save handeyeco/c4ef1a333c7ffcd8832a98d755e49a19 to your computer and use it in GitHub Desktop.
Save handeyeco/c4ef1a333c7ffcd8832a98d755e49a19 to your computer and use it in GitHub Desktop.
Placing a random vector on a sphere or between two spheres that share a (0,0,0) center (JavaScript and THREE.js)
/*
randomVectorBetweenSpheres(radius: Number, depth: Number) -> THREE.Vector3
@param radius <Number>: Radius of inner sphere (distance between center of sphere and closest possible random vector)
@param depth <Number>: Distance between inner sphere and outer sphere (radius+depth = furthest possible random vector)
*/
function randomVectorBetweenSpheres(radius, depth) {
// Create random radius between radius and radius+depth
const randomRadius = Math.floor(Math.random() * (radius + depth - radius + 1) + radius);
// Return random vector on sphere with random radius
return this.randomSphereSurfaceVector(randomRadius);
},
/*
randomSphereSurfaceVector(radius: Number) -> THREE.Vector3
@param radius <Number>: Radius of sphere on which to put a random vector
*/
function randomSphereSurfaceVector(radius) {
const theta = 2 * Math.PI * Math.random();
const phi = Math.acos(2 * Math.random() - 1);
const x = radius * Math.sin(phi) * Math.cos(theta);
const y = radius * Math.sin(phi) * Math.sin(theta);
const z = radius * Math.cos(phi);
return new THREE.Vector3(x, y, z);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment