Three.js Racing Game (Spline Track, AI Opponents)

A Three.js racing game on a closed Catmull-Rom circuit with kerbs and a start gantry, a grip-limited car handling model, pure-pursuit AI opponents that brake for corners, lap timing, and chase, cockpit and overhead cameras.

Key topics: three.js racing game, car physics, catmull rom track, ai opponents, pure pursuit, webgl racing

What this code does

- Track: a closed CatmullRomCurve3 swept into a road ribbon and kerb strips using each sample's tangent and side vector, with UVs along arc length.
- Handling: the yaw rate from the steering geometry (v·tan δ / wheelbase) is capped by tyre grip μ·g; excess lateral demand becomes a slide that decays.
- Off-Track: grass costs grip and adds rolling drag, measured as distance from the nearest centreline sample.
- AI Drivers: pure pursuit toward a speed-dependent look-ahead point, with target speed reduced by upcoming curvature (tangent dot product) and a per-driver skill.
- Laps & Position: progress is the accumulated change in arc parameter, which handles wrap-around and ranks cars.
- Controls: W/S throttle and brake, A/D steer, Space handbrake; the GUI sets autopilot, camera, opponents, grip, laps and restart.

Continue Learning

JavaScript Implementation

ES6+
// Track from a closed Catmull-Rom spline; cars follow it with pure-pursuit steering
const curve = new THREE.CatmullRomCurve3(points, true)            // closed loop

function aiSteer (car) {
  const u = nearestParam(curve, car.pos)
  const target = curve.getPointAt((u + lookAhead / curve.getLength()) % 1)
  const angle = Math.atan2(target.x - car.pos.x, target.z - car.pos.z) - car.heading
  return THREE.MathUtils.clamp(Math.atan2(Math.sin(angle), Math.cos(angle)) * 2.2, -1, 1)
}
// Grip limit: yaw rate = v·tan(steer)/wheelbase, capped so v·yawRate ≤ μ·g (else the car slides)