Collide and Slide
A kinematic controller gets a desired move every step (input direction × speed × dt, plus gravity) and must turn it into an actual move that never enters walls. The classic algorithm, used in Quake-era engines and still inside today's controllers, is collide and slide:
- Sweep the character's shape along the remaining move and find the first contact.
- Move up to the contact, stopping a small skin distance short of it.
- Project the rest of the move onto the contact plane: remove the part that points into the surface and keep the part that runs along it.
- Repeat with the projected move, up to a small maximum number of iterations (3 to 5).
The projection in step 3 is the same "subtract the normal component" you met in Projection and Reflection: rest = rest - n * dot(rest, n).
Why a skin?
If the character stopped exactly touching the wall, floating-point rounding would leave it either a hair outside or a hair inside. Inside is a disaster: the next sweep starts in contact and reports a hit at t = 0 forever. A skin of about 1 cm keeps a small gap. Unity's CharacterController.skinWidth, Godot's safe_margin (default 0.001) and Rapier's character controller offset are this idea.
Sweeping a circle against segments
In 2D, sweeping a circle of radius r against a line segment means testing two kinds of features:
- the flat side: the segment's line pushed out by
ralong its normal (a ray–line test), accepted only if the touching point lies between the ends; - the two end points: a ray against a circle of radius
raround each end (the same quadratic as Ray–Sphere).
The earliest valid t in [0, 1] wins. For an end-point hit, the contact normal points from the end point to the circle's centre, which is what makes a character slide smoothly around a corner instead of snagging.
Here a circle of radius 0.5 starts in the air and is asked to move by (6, -1): diagonally down into a floor, toward a wall.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>
struct V { double x, y; };
V operator+(V a, V b) { return {a.x + b.x, a.y + b.y}; }
V operator-(V a, V b) { return {a.x - b.x, a.y - b.y}; }
V operator*(V v, double s) { return {v.x * s, v.y * s}; }
double dot(V a, V b) { return a.x * b.x + a.y * b.y; }
double len(V v) { return std::sqrt(dot(v, v)); }
V normalize(V v) { return v * (1 / len(v)); }
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }
std::ostream& operator<<(std::ostream& os, V v) { return os << "(" << z0(v.x) << ", " << z0(v.y) << ")"; }
struct Seg { V a, b; };
struct Hit { double t; V n; };
// Earliest time t in [0, 1] at which a circle (centre p, radius r) moving by d touches segment s.
bool sweepCircle(V p, V d, double r, const Seg& s, Hit& hit) {
double best = 2; V bestN{0, 0};
V u = normalize(s.b - s.a), n{-u.y, u.x};
if (dot(p - s.a, n) < 0) n = n * -1; // normal faces the circle
double gap = dot(p - s.a, n) - r, approach = dot(d, n);
if (approach < 0) { // the flat side of the segment
double t = std::max(0.0, -gap / approach);
double along = dot(p + d * t - s.a, u);
if (t <= 1 && along >= 0 && along <= len(s.b - s.a)) { best = t; bestN = n; }
}
for (V c : {s.a, s.b}) { // the two end points
V m = p - c;
double A = dot(d, d), B = dot(m, d), C = dot(m, m) - r * r, disc = B * B - A * C;
if (B >= 0 || disc < 0) continue; // moving away, or missing
double t = std::max(0.0, (-B - std::sqrt(disc)) / A);
if (t <= 1 && t < best) { best = t; bestN = normalize(p + d * t - c); }
}
if (best > 1) return false;
hit = {best, bestN};
return true;
}
V moveAndSlide(V p, V delta, double r, const std::vector<Seg>& level, int maxIter) {
const double skin = 0.01;
for (int i = 1; i <= maxIter && len(delta) > 1e-6; i++) {
Hit hit{2, {0, 0}}, h;
for (const Seg& s : level)
if (sweepCircle(p, delta, r, s, h) && h.t < hit.t) hit = h;
if (hit.t > 1) {
p = p + delta;
std::cout << " iter " << i << ": free move to " << p << "\n";
return p;
}
double travel = std::max(0.0, len(delta) * hit.t - skin); // stop just short of contact
p = p + normalize(delta) * travel;
V rest = delta * (1 - hit.t);
rest = rest - hit.n * dot(rest, hit.n); // remove the part going into the surface
std::cout << " iter " << i << ": hit normal " << hit.n << " at " << p << ", slide by " << rest << "\n";
delta = rest;
}
return p;
}
int main() {
std::cout << std::fixed << std::setprecision(3);
std::vector<Seg> level = {
{{-10, 0}, {10, 0}}, // floor
{{4, 0}, {4, 5}}, // wall
};
double r = 0.5;
V p{0, 1};
std::cout << "move (6, -1) from " << p << "\n";
p = moveAndSlide(p, {6, -1}, r, level, 4);
std::cout << "end at " << p << "\n";
}move (6, -1) from (0.000, 1.000)
iter 1: hit normal (0.000, 1.000) at (2.990, 0.502), slide by (3.000, 0.000)
iter 2: hit normal (-1.000, 0.000) at (3.490, 0.502), slide by (0.000, 0.000)
end at (3.490, 0.502)
Two iterations tell the story. The first sweep hits the floor halfway through the move, and the remaining (3, -0.5) loses its downward part, leaving (3, 0): the character slides along the floor instead of stopping dead. The second sweep hits the wall, and projecting (0.5, 0) onto the wall's plane leaves nothing. The character ends up resting in the corner, about 1 cm from the wall.
Note: The skin is applied along the move direction here, so the gap to the floor (0.002) is smaller than the skin. Many controllers back off along the normal instead, or run a separate "depenetration" pass at the start of each move that pushes the shape out of anything it overlaps. Unity's
enableOverlapRecoveryonCharacterControlleris such a pass.
Creases and the iteration budget
In 3D, two planes meet in a line: a crease. Sliding along plane A can push into plane B, and sliding along B pushes back into A. A naive loop ping-pongs between them, shrinking the move each time and burning all its iterations. That shows up as jitter in corners and on the seam between a floor and a slanted wall.
The fix: when the projected move would go into the previous plane (dot(rest, previousNormal) < 0), slide along the crease instead, the direction cross(nA, nB), keeping only the part of the move along that line. In 2D two lines meet at a point, so the crease direction is empty and the character simply stops.
This example drops the circle into a narrow V-shaped gap:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>
struct V { double x, y; };
V operator+(V a, V b) { return {a.x + b.x, a.y + b.y}; }
V operator-(V a, V b) { return {a.x - b.x, a.y - b.y}; }
V operator*(V v, double s) { return {v.x * s, v.y * s}; }
double dot(V a, V b) { return a.x * b.x + a.y * b.y; }
double len(V v) { return std::sqrt(dot(v, v)); }
V normalize(V v) { return v * (1 / len(v)); }
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }
std::ostream& operator<<(std::ostream& os, V v) { return os << "(" << z0(v.x) << ", " << z0(v.y) << ")"; }
struct Seg { V a, b; };
struct Hit { double t; V n; };
// Earliest time t in [0, 1] at which a circle (centre p, radius r) moving by d touches segment s.
bool sweepCircle(V p, V d, double r, const Seg& s, Hit& hit) {
double best = 2; V bestN{0, 0};
V u = normalize(s.b - s.a), n{-u.y, u.x};
if (dot(p - s.a, n) < 0) n = n * -1; // normal faces the circle
double gap = dot(p - s.a, n) - r, approach = dot(d, n);
if (approach < 0) { // the flat side of the segment
double t = std::max(0.0, -gap / approach);
double along = dot(p + d * t - s.a, u);
if (t <= 1 && along >= 0 && along <= len(s.b - s.a)) { best = t; bestN = n; }
}
for (V c : {s.a, s.b}) { // the two end points
V m = p - c;
double A = dot(d, d), B = dot(m, d), C = dot(m, m) - r * r, disc = B * B - A * C;
if (B >= 0 || disc < 0) continue; // moving away, or missing
double t = std::max(0.0, (-B - std::sqrt(disc)) / A);
if (t <= 1 && t < best) { best = t; bestN = normalize(p + d * t - c); }
}
if (best > 1) return false;
hit = {best, bestN};
return true;
}
V moveAndSlide(V p, V delta, double r, const std::vector<Seg>& level, int maxIter, bool creaseAware) {
const double skin = 0.01;
bool hasFirst = false; V firstN{0, 0};
for (int i = 1; i <= maxIter && len(delta) > 1e-6; i++) {
Hit hit{2, {0, 0}}, h;
for (const Seg& s : level)
if (sweepCircle(p, delta, r, s, h) && h.t < hit.t) hit = h;
if (hit.t > 1) { p = p + delta; std::cout << " iter " << i << ": free move to " << p << "\n"; return p; }
p = p + normalize(delta) * std::max(0.0, len(delta) * hit.t - skin);
V rest = delta * (1 - hit.t);
rest = rest - hit.n * dot(rest, hit.n);
if (creaseAware && hasFirst && dot(rest, firstN) < 0) {
// Sliding along this plane would push into the previous one: we are in a crease.
// In 3D you would slide along cross(firstN, hit.n); in 2D the crease is a point, so stop.
rest = {0, 0};
}
std::cout << " iter " << i << ": hit normal " << hit.n << " at " << p << ", slide by " << rest << "\n";
if (!hasFirst) { hasFirst = true; firstN = hit.n; } else firstN = hit.n;
delta = rest;
}
return p;
}
int main() {
std::cout << std::fixed << std::setprecision(3);
std::vector<Seg> valley = { {{-3, 3}, {0, 0}}, {{0, 0}, {1, 3}} }; // a narrow V-shaped gap
double r = 0.5;
for (bool aware : {false, true}) {
V p{0.2, 3};
std::cout << (aware ? "crease-aware:\n" : "naive:\n");
p = moveAndSlide(p, {0.6, -3}, r, valley, 6, aware);
std::cout << " end at " << p << "\n";
}
}naive:
iter 1: hit normal (-0.949, 0.316) at (0.300, 2.498), slide by (-0.697, -2.090)
iter 2: hit normal (0.707, 0.707) at (-0.219, 0.939), slide by (0.174, -0.174)
iter 3: hit normal (-0.949, 0.316) at (-0.219, 0.939), slide by (-0.034, -0.102)
iter 4: hit normal (0.707, 0.707) at (-0.219, 0.939), slide by (0.031, -0.031)
iter 5: hit normal (-0.949, 0.316) at (-0.219, 0.939), slide by (-0.005, -0.016)
iter 6: hit normal (0.707, 0.707) at (-0.219, 0.939), slide by (0.002, -0.002)
end at (-0.219, 0.939)
crease-aware:
iter 1: hit normal (-0.949, 0.316) at (0.300, 2.498), slide by (-0.697, -2.090)
iter 2: hit normal (0.707, 0.707) at (-0.219, 0.939), slide by (0.000, 0.000)
end at (-0.219, 0.939)
Both versions end at the same spot, the bottom of the V where the circle touches both walls, but the naive loop spent all six iterations bouncing between the two normals with ever smaller slides. In a game that means wasted queries every frame and, with 3D rounding, visible trembling. The crease-aware version stops after the second contact.
Putting it in a controller
A full controller step usually looks like this:
// One step of a kinematic controller (outline, not runnable)
velocity.xz = input * walkSpeed; // horizontal: straight from input
velocity.y -= gravity * dt; // vertical: integrated
Vec3 desired = velocity * dt;
Vec3 moved = moveAndSlide(position, desired); // the loop from this lesson
// Remove velocity that went into walls, or the character "sticks" to ceilings and walls:
velocity = (moved - position) / dt; // or project velocity on each hit normal
position = moved;
grounded = hitFloorThisStep; // floor = a hit normal close enough to "up"Two choices hide in there:
- Separate horizontal and vertical passes. Many controllers run collide-and-slide once for the horizontal move and once for gravity. That stops gravity from making a character slide sideways down a gentle slope, and it is where the step-up logic of the next lesson plugs in.
- Update the velocity from the hits. If the character jumps into a ceiling and you keep the upward velocity, it stays glued to the ceiling until gravity cancels it. Project the velocity onto each hit plane, just like the move.
Engines do all of this for you: Unity's CharacterController.Move, Godot's CharacterBody3D.move_and_slide() (with max_slides, default 6, as its iteration budget) and Unreal's UCharacterMovementComponent all run a collide-and-slide loop with many extra rules. Knowing the loop makes their settings (skin width, max slides, wall behaviour) much easier to tune.
Test yourself
After a sweep hits a surface with normal n, what happens to the remaining move rest?
- It is discarded
- It is reflected:
rest - 2n·dot(rest, n) - It is projected onto the surface:
rest - n·dot(rest, n) - It is scaled by the restitution
What is the skin width for?
- To make the character look thicker
- To keep a small gap so rounding never leaves the shape inside a wall, where every sweep would hit at t = 0
- To speed up the broad phase
- To make the character bounce
A naive collide-and-slide loop jitters in the corner between a floor and a steep wall. What is the usual fix?
- More iterations
- A bigger skin width
- Detect the crease (sliding would go into the previous plane) and move along the crease line
cross(nA, nB) - Turn off gravity