Traffic AI path following on a road graph
aisteeringpure-pursuitpathfindingdriving-game
Making AI cars drive a city road network without riding the curb or driving through buildings came down to a few specific rules. Tuned in the Spacebar JS rebuild on a 729-node, 1,404-segment generated district.
Next hop must be a connected neighbor
The destination picker takes the previous node handle and returns a connected neighbor of it
(pickDestination(x, y, prevNode, out)). Picking "the nearest node" each time drives straight through
buildings, because the nearest node is often on a parallel street.
Leg-following pure pursuit (the big one)
Project the car onto the current from-to leg and aim at a point LOOKAHEAD = 150 px further along the leg. Aiming at the far endpoint never corrects lateral error: 60 px off-center at 1,000 px away is 3.4 degrees, under the steering deadzone, so the car rides the curb forever. Result: on-road share rose from 31% to 58 to 66%, with 0 stuck and 0 inside buildings.
Supporting constants
- ARRIVE_DIST 40 px: must be smaller than the road half-width, or cars "arrive" early and cut corners off the network.
- LOST_TIME 1.2 s: if wedged that long, drop the node handle and re-acquire from the actual position.
- Cornering brake: when the heading change ahead exceeds 0.30 rad, slow to 170 px/s, but never while crawling, or it resurrects the deadlock that a minimum creep speed (60 px/s) fixes.
- Recycling: respawn far cars (beyond about 1,900 px) at a graph node facing the travel direction. Reservoir-sample intersections so spawning never fails near map edges.
- Speeds that read well: garbage truck 72 km/h, commuter 166, sports car 281; a cop car at 380/150 is beatable.
Next step
The remaining ~40% curb clipping comes from driving the centerline. Lane discipline (offset from the leg centerline) fixes it and is a prerequisite for one-way streets and curves.
Testing
A cop pursuit AI had a deadlock found only by sweeping all 16 starting headings in a headless simulation. Keep such simulations in the repo, not a scratch directory.
See also
- Road-graph map pipeline (author roads, generate the rest)
- Arcade vehicle handling, handbrake drift and vehicle architecture