🚘 Self-Driving Car: Lane Keeping & Obstacle Avoidance
A genuine PID (Proportional-Integral-Derivative) feedback loop steers the car using a simulated lane-detection sensor — forward raycasts sampling the real road-edge geometry for lateral offset and heading error. A separate reactive layer casts rays ahead to find obstacles, computes time-to-collision, and brakes or changes lane before impact. Tune the gains badly and watch the steering oscillate — a real control-systems lesson, not a scripted path.
Scroll to adjust camera height · The car drives itself — tune the controller below
What you're seeing
The car's onboard "sensor" fires forward rays at two lookahead distances against the
road's real boundary geometry (lane dividers and edges) to measure lateral offset
e and heading error, exactly the way a lidar or lane-camera pipeline would
sample the world. The steering command is u = Kp·e + Ki·∫e dt + Kd·de/dt —
a textbook PID loop, computed fresh every frame from that sensed error, not from a
pre-baked path. A second, independent raycast layer scans ahead for traffic; when
time-to-collision drops under your threshold it either merges into a clear adjacent lane
or brakes, and the car also stops for red lights and respects the posted speed limit.
Understanding the PID Terms
Proportional (Kp) — reacts to the current error only. Too low and the car drifts sluggishly back to centre; too high and it overcorrects, swinging past the centreline and oscillating — try the "P-only" preset and watch it weave.
Integral (Ki) — accumulates past error over time, which is what finally erases the small steady-state offset a pure-P controller leaves behind. Set it too high, though, and the accumulated ("wound-up") term overshoots long after the error is gone — try "High Ki" and watch the car overshoot the centreline after a lane change.
Derivative (Kd) — reacts to how fast the error is changing, damping oscillation before it grows. It is exactly what a P-only controller is missing, but because it amplifies noise, real controllers usually keep it moderate rather than maximal.
Time-to-collision (TTC) — distance to the nearest obstacle divided by the closing speed. It is the standard automotive-safety metric behind real forward-collision-warning and automatic-emergency-braking systems; lowering the threshold here makes the car brake or swerve later and more aggressively.
About Self-Driving Car: Lane Keeping & Obstacle Avoidance
This simulation drives an autonomous vehicle down a gently curving multi-lane road using two independent control layers, both computed live every frame from simulated sensor data — nothing here follows a pre-scripted path. The lane-keeping layer fires forward raycasts against the road's real boundary geometry to estimate lateral offset and heading error, then feeds that error into a genuine PID (Proportional-Integral-Derivative) controller to compute a steering correction. The obstacle-avoidance layer independently raycasts ahead for other traffic, computes time-to-collision, and triggers braking or a lane-change manoeuvre when a collision becomes imminent, while the car also respects a posted speed limit and stops for red lights.
PID control is the workhorse of modern engineering — it steers real production ADAS lane-centring systems, stabilises drones, regulates cruise-control speed, and runs the thermostats, autopilots and industrial process loops most people interact with daily. Time-to-collision is likewise a real, standard automotive-safety metric behind forward-collision-warning and automatic-emergency-braking systems. Tuning the gains here and watching the car oscillate, overshoot, or settle smoothly is the same exercise a controls engineer runs on a real vehicle.
Frequently Asked Questions
What is a PID controller and how does it steer the car?
A PID controller computes a correction signal u from a measured error e using u = Kp·e + Ki·∫e dt + Kd·de/dt. Here e is the car's lateral offset from the lane centreline, sensed via raycasting. The proportional term reacts to the current offset, the integral term erases any small offset that lingers over time, and the derivative term reacts to how fast the offset is changing, damping oscillation. The resulting u is used directly as the car's commanded yaw rate.
How does the car "see" the lane if there's no real camera?
The simulation casts rays sideways from two points ahead of the car against the road's actual boundary meshes (lane dividers and edges), the same way a real lidar or lane-detection camera pipeline samples the physical world rather than reading a pre-known map. The distances returned by those rays are converted into a lateral offset and a heading error, which is exactly the perception step a real autonomous-driving stack performs before the control step.
What happens if I set the gains badly?
Too much Kp makes the car overcorrect and swing past the centreline, producing a visible weave that can grow into full lane-to-lane oscillation. Too much Ki makes the accumulated error term "wind up" and overshoot well after the disturbance is gone, especially after a lane change. Too little Kd removes the damping that keeps the first two terms from ringing. The presets let you jump straight to a P-only oscillation or a high-Ki windup case.
What is time-to-collision (TTC) and why use it instead of raw distance?
Time-to-collision is the distance to an obstacle divided by the closing speed (the rate the gap is shrinking). It answers "how many seconds until impact if nothing changes," which is more directly useful for a safety decision than raw distance alone — a slow-closing gap of 10 metres is far less urgent than a fast-closing gap of 10 metres. Real forward-collision-warning and automatic-emergency-braking systems in production vehicles use TTC (or closely related metrics) as their primary trigger.
How does the car decide between braking and changing lanes?
When the nearest obstacle's time-to-collision drops below your threshold, the reactive layer casts a diagonal ray toward the adjacent lane. If that ray finds no traffic within a safe gap, the car executes a lane-change manoeuvre — a smooth setpoint shift fed into the same PID loop, so the manoeuvre is steered by the identical controller, just with a temporarily offset target. If no lane is clear, the car falls back to braking, matching the obstacle's speed or stopping short.
Is raycasting a realistic stand-in for lidar and cameras?
Yes, in a simplified form. Real lidar systems fire pulsed laser beams and measure return times to build a 3D point cloud of the environment; real lane-detection cameras run image-processing pipelines to find edges. Both ultimately reduce to "which real-world surface is in this direction, and how far away." Raycasting against the scene's actual geometry captures that same core operation — querying real geometry along a direction — without the sensor noise and image processing of a full perception stack.
Why does integral windup cause overshoot?
The integral term keeps summing the error every frame for as long as the error is non-zero. During a sustained disturbance — for example while the car is still mid-lane-change and the offset hasn't reached zero yet — that sum keeps growing. Once the offset finally crosses zero, the large accumulated integral term keeps pushing the steering command in the same direction for a while longer, driving the car past the target before it can unwind, which is the overshoot you see with the "High Ki" preset.
How is this related to real autonomous-vehicle software stacks?
Production autonomous-driving stacks separate perception (sensor fusion of lidar, radar and cameras into lane and object estimates), prediction (where other agents will be), and control (translating a target trajectory into steering, throttle and brake commands) — often with a PID or a more advanced controller such as Model Predictive Control at the low level. This simulation compresses that pipeline into raycast-based perception feeding a real PID controller plus a rule-based reactive safety layer, which mirrors the same three-stage structure at a scale you can tune and observe directly.
What is a current research frontier in autonomous-vehicle control?
Beyond classical PID, real autonomous-vehicle research increasingly uses Model Predictive Control (MPC), which optimises steering and speed over a short future horizon subject to constraints like lane boundaries and other traffic, and learning-based controllers trained via imitation or reinforcement learning on large driving datasets. A major open problem is safely blending learned, data-driven policies with the verifiable guarantees that classical controllers like PID provide, particularly for rare, high-stakes edge cases such as sudden obstacle intrusions or sensor failure.