Three.js Genetic Algorithm (Evolving Smart Rockets)
Watch a genetic algorithm evolve 3D rockets to fly through obstacles to a target in Three.js, using fitness-proportional selection, single-point crossover, mutation and elitism.
Key topics: three.js genetic algorithm, evolution simulation, smart rockets, natural selection, crossover, mutation, optimization
Game Over
What this code does
- Genome: each rocket carries one thrust vector per tick (240 genes), which is the whole flight plan.
- Fitness: an exponential reward for closest approach, a big bonus for reaching the target sooner, and a penalty for crashing.
- Selection & Crossover: parents are chosen in proportion to fitness and combined at a random cut point to keep good path segments.
- Mutation: a small per-gene chance of a random thrust keeps exploring new routes; elitism keeps the best genome unchanged.
- Best Path: the yellow line replays the fittest rocket from the previous generation.
- Controls: speed, mutation rate, thrust, population size, elitism, obstacle course and restart.
Related Demos
Continue Learning
JavaScript Implementation
// Genome = one thrust vector per tick. Evolve with selection, crossover and mutation.
const LIFESPAN = 200
const target = new THREE.Vector3(0, 10, 0)
const randomGene = () => new THREE.Vector3().randomDirection().multiplyScalar(Math.random() * 0.35)
let population = Array.from({ length: 100 }, () => Array.from({ length: LIFESPAN }, randomGene))
function simulate (genes) {
const p = new THREE.Vector3(0, -9, 0)
const v = new THREE.Vector3()
let closest = Infinity
for (let t = 0; t < LIFESPAN; t++) {
v.add(genes[t]).clampLength(0, 1.2)
p.addScaledVector(v, 0.12)
closest = Math.min(closest, p.distanceTo(target))
if (closest < 0.9) return 10 + (LIFESPAN - t) / 20
}
return Math.exp(-closest / 1.5)
}
for (let gen = 0; gen < 50; gen++) {
const fitness = population.map(simulate)
const total = fitness.reduce((a, b) => a + b, 0)
const pick = () => {
let x = Math.random() * total
return population.find((_, i) => (x -= fitness[i]) <= 0) || population[0]
}
population = population.map(() => {
const a = pick()
const b = pick()
const cut = Math.floor(Math.random() * LIFESPAN)
return a.map((g, i) => (Math.random() < 0.01 ? randomGene() : (i < cut ? g : b[i]).clone()))
})
}