Pure Pursuit
Harddifficulty
Read the Pose Estimation Contract, Mecanum Kinematics, and Splines first. The basic follower only needs vectors, distances, and circle geometry.
The speed-planning part of this lesson follows Team 1712 DAWGMA's Implementation of the Adaptive Pure Pursuit Controller. Pages 5 to 9 cover adding and smoothing points, curvature, and the speed plan; pages 10 to 15 cover finding the lookahead point; pages 16 to 18 cover wheel control and tuning. The paper is written for a tank drive, and this lesson notes what's different on mecanum.
The robot knows where it is from its pose source and where it should go from a planned path. A path follower turns the path into drive commands every loop. Pure pursuit is the classic way to do it, and FTC and FRC teams have used it for years.
Waypoint-to-waypoint driving is slow and discontinuous
The obvious approach drives to waypoint 1, stops, turns, drives to waypoint 2, and so on. It's slow and jerky and hard on the drivetrain. You want the robot to follow a smooth curve at speed and correct small errors as it goes, without stopping to re-aim.
A carrot on a stick. Hold a carrot a fixed distance ahead of you, always on the path, and walk toward it. As you move, the carrot slides along the path, so you keep curving to follow it. That moving target is the lookahead point.
One arc to the lookahead point
Every loop:
- Find the lookahead point: the point on the path a fixed distance from the robot.
- Put it in the robot's frame, where is forward and is left. Call its sideways offset .
- Drive the arc: there's exactly one circle that starts at the robot, heading the way the robot is facing, and passes through the lookahead point. Drive along it.
Say in and the lookahead point is 4 in to the robot's left. The circle through it has radius in, so the robot should curve left with a radius of 50 in. In general:
is the curvature, one over the turning radius, and at speed the robot turns at . In the example, per inch, and at 30 in/s the robot turns at 0.6 rad/s. If the lookahead point is straight ahead, and the robot drives straight. The derivation is an exercise further down.
The arc rule comes from tank and car-like drives, which can only move the way they're facing and have to turn to go sideways. A mecanum drive can move in any direction whatever way it's facing, so you have two choices. You can run pure pursuit as written and treat the robot like a tank, which is simple and fine for gentle paths. That's what the code in this lesson does. Or you can drive the robot's velocity straight at the lookahead point and control heading separately, which uses what mecanum can do. PID-to-point and guided vector fields work that second way. The lookahead-point search and the speed planning below are useful either way.
The main setting is the lookahead distance:
| Lookahead | Behaviour |
|---|---|
| Too small | tracks tightly but oscillates — over-corrects and weaves |
| Too large | very smooth but cuts corners and rounds off tight features |
| Tuned | smooth tracking with stable, gentle correction |
In the demo, the robot follows the blue path and the amber dot is its lookahead point. Drag the waypoints to reshape the path, and try a small lookahead (watch it weave) and a large one (watch it cut corners).
Drag a waypoint, or Tab to it and use the arrow keys; hold Shift for a larger step. The robot keeps driving as you edit — it steers onto the new path from wherever it is.
Make a tight dog-leg with two waypoints. A small lookahead follows the corner but jitters, and a large one is smooth but cuts across it. The right value depends on the path.
Finding the carrot precisely: line–circle intersection
The lookahead point is where a circle of radius around the robot crosses the path. For one straight piece of path from to , the points on it are with from 0 to 1. You want the where that point is exactly from the robot at . Writing (the segment) and (robot to start of segment), squaring the distance gives a quadratic in :
Solve it with the quadratic formula and keep solutions between 0 and 1, since anything outside missed the segment. A few rules keep it well behaved:
- Remember how far along the path you got last loop, and only search from there forward.
- On a segment with two crossings, take the larger , the one further along.
- Skip zero-length segments (duplicate points), which would divide by zero.
- If nothing crosses and the end of the path is inside the circle, aim at the end.
- If the robot is just far from the path, keep aiming at where it last was on the path instead of jumping ahead.
// Segment A->B, robot position P, lookahead radius Ld. Returns the
// parameter t in [0, 1] where the circle crosses, or null.
Double intersect(Vector2d A, Vector2d B, Vector2d P, double Ld) {
if (!(Ld > 0)) throw new IllegalArgumentException("Ld");
Vector2d d = B.minus(A);
Vector2d f = A.minus(P);
double a = d.dot(d);
if (a < EPS) return null; // duplicate point; skip this segment
double b = 2 * f.dot(d);
double c = f.dot(f) - Ld * Ld;
double disc = b * b - 4 * a * c;
if (disc < 0) return null; // the circle never reaches this segment
double tFar = (-b + Math.sqrt(disc)) / (2 * a);
double tNear = (-b - Math.sqrt(disc)) / (2 * a);
if (tFar >= 0 && tFar <= 1) return tFar;
if (tNear >= 0 && tNear <= 1) return tNear;
return null;
}
// The "from" progress is where we were on the path last loop.
// Returns a point exactly Ld from the robot, plus the new progress.
Lookahead findLookahead(List<Vector2d> path, Vector2d robot, double Ld,
Progress from) {
for (int i = from.segment(); i < path.size() - 1; i++) {
double minT = (i == from.segment()) ? from.t() : 0;
Double t = intersect(path.get(i), path.get(i + 1), robot, Ld);
if (t != null && t >= minT) {
return new Lookahead(pointAt(path, i, t), new Progress(i, t));
}
}
Vector2d last = path.get(path.size() - 1);
if (last.minus(robot).norm() <= Ld) {
return new Lookahead(last, from); // we are finishing
}
return new Lookahead(pointAt(path, from), from); // hold; do NOT jump
}
Write "the point is exactly from " as , square both sides,
and collect powers of . Do you get the , , and in the code? What does a negative
discriminant mean on the field, and why prefer Squaring gives , and expanding gives
, the same three coefficients. A negative discriminant means the line never comes within of the robot, so the circle misses it
and there's no lookahead point on this segment. When the circle crosses a segment twice, the larger is further along the path. The smaller one is
behind the robot's target, and aiming there would stall its progress.tFar when both roots are valid?Show solution
The search starts at At the crossing, the lookahead circle hits both branches. Without the checks, the search returns
whichever comes first in the list, which is the branch the robot already drove, so it loops the first
half of the eight forever. With them, the lookahead point can only move forward along the path.from.segment() and rejects t < minT. What would a figure-eight path do
without those two checks?Show solution
Fixed vs. dynamic lookahead
The lookahead that keeps a fast straight smooth is the same one that cuts a tight corner. A fixed lookahead picks one compromise for the whole path. A dynamic lookahead changes as the robot drives:
- With speed: longer when the robot is fast, shorter when it's slow. Use the speed's size, so it still works driving backwards.
- With curvature: shorter where the path ahead bends sharply and longer on gentle sections, so tight spots are followed closely and straights stay calm.
For the speed version:
is a time: at 30 in/s with s, the lookahead is 15 in, clamped between the shortest and longest you allow. It adds settings to tune, and a lookahead that changes too suddenly causes its own steering jitter, so limit how fast it can change. If one fixed lookahead can't handle a path with both fast and tight sections, make it dynamic, or try a guided vector field, which doesn't use a lookahead point at all.
Planning speed around curves
Adaptive pure pursuit
Plain pure pursuit decides where to steer. Adaptive pure pursuit, which Team 1712 (DAWGMA) made popular in FRC, also decides how fast to go at every point, ahead of time, from the shape of the path. The robot slows for tight turns and speeds up on straights without a hand-made speed plan. It's three passes over a list of closely spaced points, plus a limit on how fast the speed can change while driving.
1. Curvature at every point. Take each point and its two neighbors, and find the circle through all three. The curvature is one over its radius. There's a neat formula for that radius using the triangle's side lengths , , and its area :
(Here is the triangle's area, not the segment endpoint from earlier.) Three points in a straight line make a triangle with no area, so the curvature is zero. The first and last points don't have two neighbors, so their curvature is set to zero.
Drag the three points below. The tighter the bend, the smaller the circle and the bigger the curvature. Line them up and it drops to zero.
2. A speed limit from curvature. Going around a curve takes sideways acceleration, , and the tires can only provide so much. Say they can hold 60 in/s² sideways. On a curve with a radius of 15 in, , so the fastest safe speed is in/s:
is the cruise speed you asked for. Some team code uses instead, which is simpler but doesn't come from the physics. The demo uses the square-root version.
3. Acceleration and braking passes. The speed limits alone can ask the robot to jump from 0 to full speed, or to hit a slow corner at full speed. Two more passes fix that. Walk forward from the robot's actual starting speed, and don't let any point be faster than the robot could reach from the point before:
where is the distance between the two points and is the acceleration limit. This is from physics class. Then walk backwards from the end, where the speed is zero, and don't let any point be faster than the robot could brake from in time to reach the next point's speed. It's the same braking formula as in PID-to-point, worked out ahead of time for the whole path:
After this pass, the robot can always slow down in time, all the way to a stop at the end.
4. A limit while driving. The passes make the plan possible to follow. While driving, also limit how much the commanded speed can change each loop:
That protects you when loop timing or the motors don't go exactly to plan.
Here's the whole plan. Drag the waypoints into a tight hairpin and watch the path turn red there as the curvature limit (blue, right) pulls the speed down, and the backward pass (orange) brings it to zero at the end. The sliders are the three settings from above.
Building the path: inject, then smooth
The speed plan needs a list of closely spaced, smooth points. You can get one from a spline, or use the simpler method from the DAWGMA paper:
- Add points every 6 in or so along each straight line between your waypoints.
- Smooth them by repeatedly nudging each point toward the average of its neighbors, while also pulling it back toward where it started:
(These and aren't the triangle sides from before.) is how hard each point is pulled toward its neighbors, usually 0.75 to 0.98, with bigger meaning smoother, and is how hard it's held near where it started. Repeat until the points stop moving much.
Update the points in place, so each point uses its neighbor's already-updated position on one side. This matters more than it looks. If you copy the list and update every point at once, it blows up for any above 1/3, so at the recommended weights the path flies off to infinity within a few dozen passes. Updated in place, it settles for any below 1.
It's simpler than fitting a spline and never overshoots, but it does pull the path a little away from your original waypoints.
Following a spline at speed
To follow a spline, turn it into a list of points spaced evenly by distance, and
store each one's turning radius from the spline's derivatives. The same speed limit
applies at each point: , so full speed on gentle curves and slower on
tight ones. (FTCclueless uses a simpler ramp, speed = 0.25 + 0.75·min(|R|, 200)/200.)
A curve also needs a centripetal feedforward. To stay on a curve of radius at speed , the robot needs sideways acceleration toward the center, . Without it, feedback only reacts once the robot has drifted outward, so it runs wide on every turn. On mecanum you can add it straight to the strafe command:
is a gain you tune. Then follow the list of points the way PID-to-point follows a list, moving on to the next point within a radius, so the robot tracks the whole curve without stopping. The code is below.
The code
One loop: find the lookahead point, put it in the robot's frame, turn that into a curvature, and send a forward speed and turn rate.
private Progress progress = new Progress(0, 0); // persistent across loops
void start() {
progress = new Progress(0, 0);
timer.reset();
}
MoveStatus update(List<Vector2d> path, Pose2d endPose) {
if (path.size() < 2 || !(LOOKAHEAD > 0)) throw new IllegalStateException();
PoseSample sample = poseSource.getSample(); // once, at the loop top
Pose2d robot = sample.pose();
if (moveStatus(sample, endPose, timer.seconds()) == TIMED_OUT) {
drive(0, 0, 0);
return TIMED_OUT; // the deadline applies in every phase
}
Lookahead look = findLookahead(path, robot.vec(), LOOKAHEAD, progress);
progress = look.progress();
Vector2d d = look.carrot().minus(robot.vec()); // into the robot frame
double yLocal = -Math.sin(robot.heading()) * d.x()
+ Math.cos(robot.heading()) * d.y();
double L = d.norm();
if (progress.segment() == path.size() - 2
&& (progress.t() >= 1.0
|| (progress.t() > TERMINAL_T
&& robot.vec().minus(endPose.vec()).norm() < HANDOFF))) {
return terminalController.update(sample, endPose);
}
if (L < EPS) {
drive(0, 0, 0);
return RUNNING; // zero chord: wait for a real target
}
double curvature = 2 * yLocal / (L * L);
double v = CRUISE; // inches/second
double omega = curvature * v; // radians/second
drive(v / MAX_SPEED, 0, omega / MAX_TURN); // normalize at the mixer boundary
return RUNNING;
}
Near the end, control passes to the shared terminal pose controller, and that's the only place
REACHED can come from.
In the robot's frame, the arc starts at the origin heading along . So the circle's center is
somewhere on the axis, at . The lookahead point is on the circle, and its distance
from the robot is . Find . A point on the circle satisfies , which simplifies to . The left
side is , so and .Show solution
What happens to an autonomous routine if its follower can report It moves on early. The routine thinks the path is done and starts the next action, scoring or another
drive, while the robot is still in the middle of the field, and every move after that starts from the
wrong place. Only letting the terminal controller say REACHED in the middle of the path?Show solution
REACHED means it can only come from code that
has actually checked the end position, heading, and speed.
Road Runner follows full trajectories, a path plus a motion profile in time, with feedforward and PID on top. Pedro Pathing instead works out its target from where the robot actually is on the path each loop and combines several correction terms (see How Does Pedro Pathing Work?). Both handle speed and accuracy more carefully than basic pure pursuit.
The speed plan is worked out once, ahead of time: curvature at each point, a speed limit from it, then the two passes.
// aLatMax is the sideways acceleration the tires hold; aMax the forward
// acceleration and braking limit; startSpeed how fast the robot is now.
void planProfile(List<PathPoint> pts, double vPath, double aLatMax,
double aMax, double startSpeed) {
for (int i = 1; i < pts.size() - 1; i++) { // endpoints stay at zero
pts.get(i).curvature =
mengerCurvature(pts.get(i - 1), pts.get(i), pts.get(i + 1));
}
for (PathPoint p : pts) { // slower where it bends
p.speed = Math.abs(p.curvature) < EPS
? vPath
: Math.min(vPath, Math.sqrt(aLatMax / Math.abs(p.curvature)));
}
pts.get(0).speed = Math.min(pts.get(0).speed, startSpeed);
for (int i = 1; i < pts.size(); i++) { // cannot speed up past aMax
double ds = pts.get(i).minus(pts.get(i - 1)).norm();
double reachable = Math.sqrt(
pts.get(i - 1).speed * pts.get(i - 1).speed + 2 * aMax * ds);
pts.get(i).speed = Math.min(pts.get(i).speed, reachable);
}
pts.get(pts.size() - 1).speed = 0;
for (int i = pts.size() - 2; i >= 0; i--) { // must still brake to a stop
double ds = pts.get(i + 1).minus(pts.get(i)).norm();
double reachable = Math.sqrt(
pts.get(i + 1).speed * pts.get(i + 1).speed + 2 * aMax * ds);
pts.get(i).speed = Math.min(pts.get(i).speed, reachable);
}
}
double mengerCurvature(Vector2d A, Vector2d B, Vector2d C) {
double area = Math.abs(B.minus(A).cross(C.minus(A))) / 2;
double denom = B.minus(C).norm() * A.minus(C).norm() * A.minus(B).norm();
if (denom < EPS) return 0; // the three points are collinear
return 4 * area / denom;
}
mengerCurvature gives one over the radius of the circle through three points without actually
finding the circle. While driving, limit changes using the measured loop time:
double target = pts.get(closestIndex).speed;
double maxStep = A_MAX * measuredDt;
commanded += clamp(target - commanded, -maxStep, +maxStep);
Why does a tighter corner have to mean a lower speed, and what happens if the robot goes faster? And
what would the plan look like with only the forward pass? A curve of radius at speed needs of sideways acceleration, and only tire grip provides
it. Halve the radius and you need twice as much at the same speed. Past the grip limit, the tires slide,
the robot runs wide, and the odometry is now wrong too. With only the forward pass, the plan speeds up to cruise and stays there, and nothing slows it down. The
robot reaches the last point at full speed and overshoots, braking only when the terminal controller
notices. The backward pass makes the plan itself end at zero, so the braking is planned instead of a
reaction.Show solution
To follow a spline, resample it, step through the points, limit speed by each point's radius, and add the centripetal feedforward:
// Each SplinePoint holds x, y, heading, radius and speed.
List<SplinePoint> resample(Spline spline, double step) {
if (!(step > 0)) throw new IllegalArgumentException("step");
List<Double> distances = new ArrayList<>();
for (double d = 0; d < spline.length(); d += step) distances.add(d);
distances.add(spline.length()); // the exact endpoint, always
List<SplinePoint> out = new ArrayList<>();
double previousHeading = 0;
for (double d : distances) {
double t = spline.tAtDistance(d);
double dx = spline.dx(t), dy = spline.dy(t);
double ddx = spline.ddx(t), ddy = spline.ddy(t);
double speedSq = dx * dx + dy * dy;
double heading, curvature;
if (speedSq > EPS) {
heading = Math.atan2(dy, dx);
curvature = (dx * ddy - dy * ddx) / Math.pow(speedSq, 1.5);
} else {
heading = previousHeading; // a cusp; atan2(0,0) is meaningless
curvature = 0;
}
previousHeading = heading;
double radius = Math.abs(curvature) < EPS
? Double.POSITIVE_INFINITY
: 1 / curvature;
out.add(new SplinePoint(spline.x(t), spline.y(t), heading, radius, 0));
}
return out;
}
tAtDistance is needed because equal steps in the spline's aren't equal distances along it.
// Caps each point by its radius, then runs the same forward and backward
// passes as planProfile. Returns NEW points; never mutates the input.
List<SplinePoint> planSpeeds(List<SplinePoint> points, double cruise,
double aLatMax, double aMax, double startSpeed) {
...
}
void start(Spline spline) {
active = planSpeeds(resample(spline, SPACING), CRUISE,
A_LAT_MAX, A_MAX, poseSource.getSample()
.fieldVelocity().norm());
index = 0;
timer.reset();
}
MoveStatus update() {
PoseSample sample = poseSource.getSample();
Pose2d robot = sample.pose();
SplinePoint end = active.get(active.size() - 1);
if (moveStatus(sample, end.pose(), timer.seconds()) == TIMED_OUT) {
drive(0, 0, 0);
return TIMED_OUT;
}
while (index < active.size() - 1
&& robot.vec().minus(active.get(index).vec()).norm() < PATH_RADIUS) {
index++; // advance only; never walk back
}
if (index == active.size() - 1) {
return terminalController.update(sample, end.pose());
}
SplinePoint p = active.get(index);
double speed = p.speed(); // the final planned point is exactly 0
double ex = p.x() - robot.x(), ey = p.y() - robot.y();
double c = Math.cos(robot.heading()), s = Math.sin(robot.heading());
double dir = Math.atan2(ey * c - ex * s, ex * c + ey * s);
double vx = speed * Math.cos(dir);
double vy = speed * Math.sin(dir);
vy += K_CENTRIPETAL * speed * speed / p.radius(); // lean into the corner
// headingController already returns normalized power; vx and vy are in/s.
drive(vx / MAX_SPEED, vy / MAX_SPEED, headingController(p.heading()));
return RUNNING;
}
A spline is 10.5 long and The distances run 0 through 10, so the last half inch is never sampled and the final point is at 10.0
instead of 10.5. The robot ends every path half an inch short, which looks like a tuning problem but
isn't.step = 1.0. List the distances without that last line. Which point is
missing, and what does the follower do?Show solution
What does the follower do on a curve without the centripetal term? And why does Without it, the follower only corrects once it has drifted to the outside of the corner, so every bend
starts wide and gets fixed late, and it gets worse with speed squared. The feedforward supplies the
sideways push the curve needs before any error shows up.K_CENTRIPETAL have
units of seconds?Show solution
speed^2 / radius is , an acceleration, and
it's added to vy, a velocity in in/s. So K_CENTRIPETAL has to be in seconds.
The whole plan is in inches per second and radians per second, and it's only converted to motor units
in the drive(...) call, which takes normalized power. Every speed is divided by MAX_SPEED or
MAX_TURN on the way in. Pass raw inches per second and drive scales everything to full power.
The speed limit is only as smooth as the curvature. A path that only matches direction at each waypoint, like a cubic Hermite or Catmull-Rom spline, has curvature that jumps at every join, so the speed limit jumps too. Quintic and natural cubic splines have continuous curvature, as long as the path never stops dead, so the speed plan is smooth.
A tank drive turns curvature and speed straight into wheel speeds. With meaning a left turn and a track width , the left side gets and the right side . Using a track width a few inches wider than the real one helps account for wheel scrub when turning. (On mecanum, the same and go into the mixer.)
The last lesson in this module, Guided Vector Fields, follows a path without a lookahead point at all.
The techniques on this page are adapted, with attribution, from these references and open-source repositories:
- Adaptive pure pursuit — curvature velocity profile, inject-and-smooth path generation, signed curvature, differential-drive wheel split: Team 1712 (DAWGMA), Implementation of the Adaptive Pure Pursuit Controller — download the attached whitepaper or open its Chief Delphi publication page. Start here for a complete implementation sequence and practical tuning notes.
- The original pure-pursuit derivation: R. C. Coulter, Implementation of the Pure Pursuit Path Tracking Algorithm, CMU Robotics Institute, 1992 (PDF).
- Interactive reference implementation — xiaoxiae/PurePursuitAlgorithm (an adaptive pure-pursuit visualiser).
- The path-smoothing pass: KHEngineering/SmoothPathPlanner (the gradient-descent smoother the DAWGMA paper borrows from Team 2168).
- Line–circle intersection lookahead: FTCclueless/Centerstage
(
subsystems/drive/Drivetrain.java,lineCircleIntersection). - Spline following with curvature speed scaling and centripetal feedforward (resample to points
carrying , cap speed by , add a strafe term) —
FTCclueless/Centerstage (
subsystems/drive/Spline.javaandDrivetrain.java).
The code here is an independent reimplementation of these ideas, not a copy of any one source.