Three.js N-Body Gravity Simulation (Galaxy Collision)

Direct-summation N-body gravity in Three.js with leapfrog integration and Plummer softening, covering colliding disk galaxies, a rotating disk, an equilibrium Plummer sphere and cold collapse, with live energy and virial diagnostics.

Key topics: three.js n-body, gravity simulation, galaxy collision, leapfrog integrator, plummer sphere, astrophysics, particles

What this code does

- Direct Summation: every pair interaction is computed (O(N²)) and Newton's third law halves the work.
- Softening: forces use 1/(r² + ε²)^(3/2) to avoid singular close encounters between point masses.
- Leapfrog (KDK): kick–drift–kick is symplectic, so energy error stays bounded; the HUD shows the drift as a percentage.
- Galaxy Collision: two rotating disks with massive cores on a bound orbit throw off tidal tails and bridges as they merge.
- Plummer Sphere: positions and speeds sampled from the Plummer distribution start in virial equilibrium (2K/|U| ≈ 1).
- Controls: initial conditions, body count, steps per frame, time step, softening, point size and restart.

Continue Learning

JavaScript Implementation

ES6+
// Direct-summation N-body with leapfrog (G = 1)
const n = 800
const pos = new Float32Array(n * 3).map(() => (Math.random() - 0.5) * 16)
const vel = new Float32Array(n * 3)
const acc = new Float32Array(n * 3)
const m = 4 / n
const eps2 = 0.04

function accelerations () {
  acc.fill(0)
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      const dx = pos[j * 3] - pos[i * 3]
      const dy = pos[j * 3 + 1] - pos[i * 3 + 1]
      const dz = pos[j * 3 + 2] - pos[i * 3 + 2]
      const r2 = dx * dx + dy * dy + dz * dz + eps2
      const f = m / (r2 * Math.sqrt(r2))
      acc[i * 3] += dx * f; acc[i * 3 + 1] += dy * f; acc[i * 3 + 2] += dz * f
      acc[j * 3] -= dx * f; acc[j * 3 + 1] -= dy * f; acc[j * 3 + 2] -= dz * f
    }
  }
}

const geometry = new THREE.BufferGeometry()
geometry.setAttribute('position', new THREE.BufferAttribute(pos, 3))
scene.add(new THREE.Points(geometry, new THREE.PointsMaterial({ size: 0.15, color: 0x9fc5ff })))

accelerations()

function animate () {
  requestAnimationFrame(animate)
  const dt = 0.01
  for (let i = 0; i < n * 3; i++) vel[i] += acc[i] * dt / 2
  for (let i = 0; i < n * 3; i++) pos[i] += vel[i] * dt
  accelerations()
  for (let i = 0; i < n * 3; i++) vel[i] += acc[i] * dt / 2
  geometry.attributes.position.needsUpdate = true
  renderer.render(scene, camera)
}
animate()