← Home

How to place dots evenly in the sphere

Recently, I watching Akela’s stream about create a sphere with dots in Threejs. So I decided to write a post about it. The url of the stream is here.

There are several ways to place dots evenly in the sphere. I will use the golden ratio method. Golden ratio is a special number approximately equal to 1.6180. We can use this formular to create golden ratio:

const goldenRatio = (1 + Math.sqrt(5)) / 2;

Let’s create a sphere with dots in Threejs. First, we need to create a sphere:

const geometry = new THREE.IcosahedronGeometry(1, 10);
const material = new THREE.MeshBasicMaterial({
  color: 0xffffff,
  wireframe: true,
});
const sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);

Then, we need to place dots in the sphere. We can use the golden ratio method to place dots evenly in the sphere:

const dotsNumber = 30000;

for (let i = 0; i < dotsNumber; i++) {
  const progress = i / dotsNumber;
  const theta = (2 * Math.PI * i) / golderRatio;
  const phi = Math.acos(1 - 2 * prog);
  const x = Math.cos(theta) * Math.sin(phi);
  const z = Math.sin(theta) * Math.sin(phi);
  const y = Math.cos(phi);

  const u = 1 - (Math.asin(y) / Math.PI + 0.5);
  const v = 1 - (Math.atan2(z, x) + Math.PI) / (2 * Math.PI);

  if (pixels[Math.floor(v * size)][Math.floor(u * size)]) {
    positions.push([x, y, z]);
  }
}

Explanation of the code:

  • dotsNumber: number of dots in the sphere. Default is 30000.
  • progress: progress of the loop, from 0 to 1.
  • theta: angle of the dot in the sphere in the xz plane.
  • phi: angle of the dot in the sphere in the yz plane.