Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a random Vector3 within a sphere?

I am trying to create a random point within a sphere, and I am not sure how to do this. I came up with this but I think it is returning a point within a cube I think I have to do something with Math.PI but not sure how.

  #createParticlePosition() {
    const shape = this.options.shape;
    // shape.radius = 2;
    if (shape.type === 'sphere') {
      return new Three.Vector3(
        (Math.random() * shape.radius - (shape.radius / 2)) * 1.0,
        (Math.random() * shape.radius - (shape.radius / 2)) * 1.0,
        (Math.random() * shape.radius - (shape.radius / 2)) * 1.0
      );
    }
  }
like image 584
Get Off My Lawn Avatar asked Jan 28 '26 16:01

Get Off My Lawn


1 Answers

You are indeed just creating boxes. You're only calculating the x,y,z values linearly, not spherically. Three.js has a Vector3.randomDirection method that could do these calculations for you:

const maxRadius = 2;

// Randomize to range [0, 2]
const randomRadius = Math.random() * maxRadius;

// Create vec3
const randomVec = new THREE.Vector3();

// Make vector point in a random direction with a radius of 1
randomVec.randomDirection();

// Scale vector to match random radius
randomVec.multiplyScalar(randomRadius);

This method utilizes this approach internally to avoid density accumulation in the poles.

enter image description here

like image 191
Marquizzo Avatar answered Jan 30 '26 04:01

Marquizzo