0 Spicy Yoghurt | Last updated: 16 November 2026 | Algorithm tutorial
Steering behaviors in JavaScript: seek, flee, arrive, wander and more
Learn to code steering behaviors in JavaScript, from seek and arrive to wander, pursue and path following. Every behavior is a short method you can copy, with a live demo on the HTML5 canvas to play with. Then combine them, and your game characters will find their own way around.
Move your mouse over the pond below, or touch it, and the mother duck swims toward your mouse or finger. Her ducklings follow her in a row, the fish swim around under the lily pads, and the heron keeps trying to catch the frog. Every animal in the pond moves with the steering behaviors from this page:
What are steering behaviors?
In a game, lots of characters move around on their own. A guard patrols a room, a zombie chases the player and a fish swims around in a tank. They don't follow a fixed route. Instead, they decide every frame which way to go, based on what's around them. Steering behaviors are a simple and popular way to do that.
Craig Reynolds described them in 1999, in a paper called Steering Behaviors For Autonomous Characters, which he presented at the Game Developers Conference. He's the same Craig Reynolds who came up with boids, the simulated birds from the tutorial about flocking with boids.
Reynolds splits the movement of a character into three layers. He illustrates them with a cowboy herding cattle, and a cow that wanders away from the herd:
- Action selection - The trail boss notices the stray cow and tells the cowboy to bring it back. This layer decides what a character wants to do.
- Steering - The cowboy guides his horse to the cow, around anything that's in the way. This layer decides which way to go to get there.
- Locomotion - The horse does the walking. This layer moves the character, with legs, wheels or wings.
This page is about the middle layer. The top layer is often a state machine that switches between behaviors, like the one in the tutorial about game states. In a 2D game, the bottom layer can be as simple as moving the character a little bit every frame.
Every steering behavior works the same way. It looks at where the character is and what's around it, and returns a force that pushes the character in a direction. A character can use several behaviors at the same time, by adding up their forces. The next section sets up the steering force. After that, each section covers one behavior, with the code, a demo and the problems you'll run into. Most behaviors stand on their own, so you can skip straight to the ones you need.
The steering force in a nutshell
Recap - The tutorial about flocking with boids builds the steering force step by step, with a demo that shows every force as an arrow. This section sums it up in a class that you'll use in every section of this page.
Reynolds calls a character that steers itself a vehicle. In his paper, a vehicle can be anything that moves, from a car to a horse. On this page, it's a duck, a fish, a car or a guard. A vehicle has a position, x and y, and a velocity, vx and vy, in pixels per second. It also has a maxSpeed, how fast it can go, and a maxForce, how hard it can steer.
Each frame, a behavior works out a desired velocity: the velocity the vehicle would like to have, at full speed in the direction it wants to go. The steering force changes the current velocity toward the desired velocity, but never by more than maxForce pixels per second, every second. So a vehicle turns and speeds up gradually, instead of changing direction in a single frame. Here's the class:
// How fast a vehicle reacts, in seconds
const reactionTime = 0.1;
class Vehicle {
constructor(x, y, maxSpeed, maxForce) {
this.x = x;
this.y = y;
this.vx = 0;
this.vy = 0;
this.ax = 0;
this.ay = 0;
this.maxSpeed = maxSpeed;
this.maxForce = maxForce;
this.angle = 0;
}
// Steer in the direction (x, y) at the given speed
steer(x, y, speed = this.maxSpeed) {
let length = Math.hypot(x, y);
if (length == 0) {
return {x: 0, y: 0};
}
// The desired velocity: the direction at the given speed
let desiredX = x / length * speed;
let desiredY = y / length * speed;
// The difference from the current velocity
let steerX = (desiredX - this.vx) / reactionTime;
let steerY = (desiredY - this.vy) / reactionTime;
let force = Math.hypot(steerX, steerY);
if (force > this.maxForce) {
steerX *= this.maxForce / force;
steerY *= this.maxForce / force;
}
return {x: steerX, y: steerY};
}
applyForce(force, weight = 1) {
this.ax += force.x * weight;
this.ay += force.y * weight;
}
update(secondsPassed) {
this.vx += this.ax * secondsPassed;
this.vy += this.ay * secondsPassed;
this.ax = 0;
this.ay = 0;
// Never move faster than maxSpeed
let speed = Math.hypot(this.vx, this.vy);
if (speed > this.maxSpeed) {
this.vx *= this.maxSpeed / speed;
this.vy *= this.maxSpeed / speed;
}
this.x += this.vx * secondsPassed;
this.y += this.vy * secondsPassed;
// Face the way it's moving, but not when it stands still
if (speed > 1) {
this.angle = Math.atan2(this.vy, this.vx);
}
}
}steer() takes a direction, x and y, and a speed. Dividing the direction by its length gives it a length of 1, and multiplying by the speed turns it into the desired velocity. Most behaviors steer at full speed, so speed is maxSpeed unless you pass something else.
The difference between the desired velocity and the current velocity is how much the velocity has to change. reactionTime is how many seconds the vehicle would take to make that change, if nothing held it back. maxForce does hold it back: if the force is bigger than maxForce, steer() scales it down without changing its direction. When the difference is big, maxForce decides how fast the velocity changes. When it's small, like when a vehicle is almost at its desired speed, reactionTime decides. In the flocking tutorial, steer() uses the difference as is, which is the same as a reactionTime of 1 second. That's fine for a flock, but a vehicle that has to stop at a target would react too slowly and shoot past it.
applyForce() adds a force to the acceleration, ax and ay. A vehicle has a mass of 1, so a force and an acceleration are the same thing. Some behaviors are more important than others, so you can give a force a weight. update() uses the acceleration to change the velocity, and then resets the acceleration to 0 for the next frame. It also caps the speed at maxSpeed, because several forces together can push the vehicle past it.
angle is the direction the vehicle faces. update() only changes it while the vehicle is moving, so a vehicle that stops keeps facing the same way. The example code at the end of this page also has a draw() method, which draws the vehicle as a triangle that points in that direction.
Every behavior on this page is a method of the Vehicle class that returns a force. In the game loop, you pass that force to applyForce(), and then you move the vehicle:
// In the game loop, for every vehicle
vehicle.applyForce(vehicle.seek(target.x, target.y));
vehicle.update(secondsPassed);seek() is the first behavior, which you'll meet in the next section, and target is the point the vehicle steers toward: anything with an x and a y. secondsPassed is the time since the last frame, in seconds. The tutorial about smooth canvas animation explains how to measure it, and why update() multiplies by it: that way, a vehicle moves at the same speed on every screen. The example code at the end of this page has a complete game loop.
Seek and flee: move toward or away from a target
Seek is the simplest steering behavior: the vehicle steers toward a target. Flee is the opposite. The vehicle steers away from the target, but only when the target is closer than fleeRadius. Without that limit, it would run from a target on the other side of the screen. Add both methods to the Vehicle class:
const fleeRadius = 150;
// In the Vehicle class
seek(x, y) {
return this.steer(x - this.x, y - this.y);
}
flee(x, y) {
let dx = this.x - x;
let dy = this.y - y;
if (Math.hypot(dx, dy) > fleeRadius) {
return {x: 0, y: 0};
}
return this.steer(dx, dy);
}Both methods take the position of the target, x and y. Seek steers in the direction from the vehicle to the target, and flee in the direction from the target to the vehicle. Math.hypot() gives the length of that direction, which is the distance between the two.
Move your mouse over the canvas below, or touch it, and the red dot follows your mouse or finger. If you don't, the dot moves around by itself. The blue arrow is the current velocity of the vehicle, the gray arrow is the desired velocity and the red arrow is the steering force. Switch between Seek and Flee:
With Seek, the vehicle chases the dot at full speed. When the dot stops, the vehicle shoots past it and has to turn around, again and again. With Flee, the vehicle only steers while it's inside the dashed circle around the dot. Once it's outside, flee() returns no force, and nothing slows the vehicle down, so it keeps drifting in the same direction. In the demo, a vehicle that leaves the canvas on one side comes back on the other, like the boids in the flocking tutorial.
Seek works well for a target that keeps moving, like the player. For a target that stays put, you need the next behavior.
Arrive: slow down near the target
Imagine a character that walks to a spot you clicked. With seek, it reaches the spot at full speed, shoots past it, turns around and shoots past it again. Arrive fixes that. It works like seek, but within slowRadius of the target, the vehicle slows down, until it stops right on top of it:
const slowRadius = 120;
// In the Vehicle class
arrive(x, y, radius = slowRadius) {
let dx = x - this.x;
let dy = y - this.y;
let distance = Math.hypot(dx, dy);
// Within the radius, slow down to 0 at the target
let speed = this.maxSpeed;
if (distance < radius) {
speed = this.maxSpeed * distance / radius;
}
return this.steer(dx, dy, speed);
}Far from the target, the desired speed is maxSpeed, just like with seek. Within radius of the target, the speed drops steadily, from maxSpeed at the edge of the circle to 0 at the target. That's what the speed parameter of steer() is for. radius is slowRadius, unless you pass a different one. That comes in handy later on this page, when the ducklings follow their mother.
Click or tap the canvas below to put the target somewhere else. If you don't, the target moves to a new spot every few seconds. The blue line shows where the vehicle went, and the number in the corner is its speed. Compare Seek with Arrive:
With Arrive, the vehicle slows down inside the dashed circle and stops right on top of the dot. That only works if the vehicle can brake in time. Braking as hard as it can, a vehicle at full speed needs maxSpeed² / (2 × maxForce) pixels to stop. That's the standard formula for braking at a constant rate. The vehicle in the demo has a maxSpeed of 200 and a maxForce of 250, so it needs 80 pixels, and a slowRadius of 120 gives it room to spare. Make slowRadius smaller than 80, and the vehicle still overshoots.
Pursue and evade: predict where another character is going
A chaser that seeks a moving target always runs to where the target is now. By the time it gets there, the target has moved on, so the chaser ends up trailing behind. Pursue is smarter: it predicts where the target will be, and seeks that spot instead.
To predict where the target will be, multiply its velocity by a number of seconds, and add the result to its position. Reynolds suggests a prediction time that grows with the distance, so a chaser that's far away looks further ahead. Here, it's the distance divided by the chaser's own maxSpeed: about the time the chaser needs to get there. maxPredictTime keeps it from looking too far ahead when the target is far away:
const maxPredictTime = 1;
// In the Vehicle class
predict(target) {
let dx = target.x - this.x;
let dy = target.y - this.y;
// Roughly the time it takes to get there
let time = Math.hypot(dx, dy) / this.maxSpeed;
time = Math.min(time, maxPredictTime);
return {
x: target.x + target.vx * time,
y: target.y + target.vy * time
};
}
pursue(target) {
let future = this.predict(target);
return this.seek(future.x, future.y);
}
evade(target) {
let future = this.predict(target);
return this.flee(future.x, future.y);
}This time, target is another Vehicle, so it has a position and a velocity. Evade is the opposite of pursue: the vehicle flees from the spot where the other character is going, instead of from where it is now. Like flee, it only reacts when that spot is closer than fleeRadius.
In the canvas below, the red vehicle chases the blue one, which drives around the dashed loop at a fixed speed. The red vehicle is only a little faster. With Pursue, the red circle shows where it expects the blue vehicle to be. The timer in the corner shows how long each chase takes:
With Seek, the chaser follows the blue vehicle around the loop, and it takes a while to catch up. With Pursue, it cuts across the loop and catches the blue vehicle a lot sooner. The prediction isn't perfect, because it assumes the target keeps going in a straight line. When the target turns, the prediction changes, and the chaser turns with it. The frog in the pond at the top of this page uses evade to stay away from the heron.
Pursue doesn't know about walls. If a character has to chase the player through a maze, the tutorial about pathfinding shows you how to find a route around the walls, and how to update that route while the player moves.
Wander: move around without a goal
Not every character has a target. A fish in a tank or a guard on patrol just needs to move around in a way that looks natural. A common first idea is to steer in a random direction every frame. But then every frame pulls the vehicle in a different direction, and the random pulls cancel each other out. The vehicle just jitters in place.
Reynolds' wander behavior keeps the randomness small, and lets it add up over time. Picture a circle in front of the vehicle, with a point on its edge. Every frame, the point moves a tiny bit along the edge, to the left or to the right, and the vehicle seeks the point. Because the point only moves a little at a time, the vehicle turns smoothly, sometimes one way and sometimes the other.
Give the vehicle a wanderAngle: the angle of the point on the circle, relative to the direction the vehicle faces. Add this.wanderAngle = 0; to the constructor, and add a wander() method:
const wanderDistance = 60;
const wanderRadius = 30;
const wanderChange = 4;
// In the Vehicle class
wander(secondsPassed) {
// Move the point a little bit along the circle
let change = Math.random() * 2 - 1;
this.wanderAngle += change * wanderChange * secondsPassed;
// The center of the circle, in front of the vehicle
let headingX = Math.cos(this.angle);
let headingY = Math.sin(this.angle);
let centerX = this.x + headingX * wanderDistance;
let centerY = this.y + headingY * wanderDistance;
// The point on the circle
let angle = this.angle + this.wanderAngle;
let targetX = centerX + Math.cos(angle) * wanderRadius;
let targetY = centerY + Math.sin(angle) * wanderRadius;
return this.seek(targetX, targetY);
}Math.random() * 2 - 1 is a random number from -1 to 1. Negative numbers move the point one way, and positive numbers the other way. The tutorial about random numbers in JavaScript explains how to get random numbers in any range you need. wanderChange is how fast the point can move along the circle, in radians per second. Angles in JavaScript are in radians: a full circle is 2π, about 6.28 radians. The center of the circle is wanderDistance in front of the vehicle, and the point is wanderRadius away from the center.
The red vehicle in the demo below shows its circle and the point it seeks. Switch between Random direction and Wander:
With Wander, the vehicles drift around in long, lazy curves. To make them turn more sharply, make the circle bigger, or move it closer to the vehicle. A bigger wanderChange makes them change direction more often.
Avoid round obstacles by looking ahead
In the flocking tutorial, the boids avoid obstacles by steering away from the center of every obstacle that's too close. That works for a flock in open space, but it has a weak spot. A vehicle that heads straight for the center of an obstacle gets pushed straight back. Its target pulls it forward and the obstacle pushes it back, so it nearly stops in front of the obstacle and only slowly slides off to one side.
Reynolds' obstacle avoidance looks ahead instead. Picture a strip in front of the vehicle, as wide as the vehicle and longer when it goes faster. Only an obstacle that overlaps the strip is in the way. The vehicle steers sideways, away from the nearest one, long before it gets close. Here's the method, for obstacles that are circles with an x, a y and a radius:
const avoidLength = 100;
const vehicleRadius = 10;
// In the Vehicle class
avoidObstacles(obstacles) {
let speed = Math.hypot(this.vx, this.vy);
if (speed == 0) {
return {x: 0, y: 0};
}
// The direction it's moving in, with a length of 1
let forwardX = this.vx / speed;
let forwardY = this.vy / speed;
// Look further ahead when it moves faster
let ahead = avoidLength * speed / this.maxSpeed;
let nearest = null;
let nearestAlong = 0;
let nearestSide = 0;
for (let obstacle of obstacles) {
let dx = obstacle.x - this.x;
let dy = obstacle.y - this.y;
// How far ahead it is, and how far to the side
let along = dx * forwardX + dy * forwardY;
let side = dx * forwardY - dy * forwardX;
// Skip obstacles behind the vehicle or too far ahead
if (along < 0 || along > ahead + obstacle.radius) {
continue;
}
// Skip obstacles that the vehicle will miss
let clearance = obstacle.radius + vehicleRadius;
if (Math.abs(side) > clearance) {
continue;
}
if (nearest == null || along < nearestAlong) {
nearest = obstacle;
nearestAlong = along;
nearestSide = side;
}
}
if (nearest == null) {
return {x: 0, y: 0};
}
// Steer right when the obstacle is on the left, and left
// when it's on the right
let turn = nearestSide > 0 ? 1 : -1;
let force = this.steer(-forwardY * turn, forwardX * turn);
// Steer harder when the obstacle is closer
let range = ahead + nearest.radius;
let strength = 1 - nearestAlong / range;
return {x: force.x * strength, y: force.y * strength};
}forwardX and forwardY are the direction the vehicle is moving in. For each obstacle, along is how far ahead of the vehicle the center of the obstacle is, and side is how far it is to the side. along is the dot product of the vector to the obstacle and the forward direction. The tutorial about collision detection explains the dot product. side is the same dot product, but with the forward direction rotated a quarter turn to the left: (forwardY, -forwardX). That's where the swap and the minus sign come from. A negative along means the obstacle is behind the vehicle. A positive side means it's on the left, and a negative one that it's on the right.
The obstacle is in the way when it's ahead of the vehicle, not too far ahead, and less than its radius plus vehicleRadius to the side. The method steers away from the nearest of those, at a right angle to the way the vehicle is going. (-forwardY, forwardX) points to the right of the vehicle, and turn flips it to the left when the obstacle is on the right. strength makes the force stronger the closer the obstacle is.
Each vehicle in the demo below drives straight to the right, until an obstacle gets in the way. Click or tap the canvas to place an obstacle, and click or tap an obstacle to remove it. Switch between Push away, the method from the flocking tutorial, and Look ahead. With Look ahead, the red vehicle shows its strip:
With Push away, a vehicle that heads for the center of an obstacle almost stops in front of it, and then creeps around it. With Look ahead, it swerves early and keeps most of its speed. Pushing away is fine for a flock in open space, where boids rarely head straight for an obstacle. Looking ahead is better for characters that travel to a goal. For walls, which aren't round at all, you need the next behavior.
Use feelers to stay away from walls
Walls are long and thin, so a circle doesn't fit them. A common trick in games is to give the vehicle feelers, like a cat's whiskers. These are three lines that stick out in front of it: one straight ahead, and a shorter one to each side. When a feeler crosses a wall, the vehicle steers away from the wall, as hard as it can.
Each wall is a line segment from (x1, y1) to (x2, y2). To find out whether a feeler crosses a wall, you need the point where two line segments meet. This function finds it:
// Where the line from start to end crosses the wall, as a number
// from 0 at start to 1 at end, or null if they don't cross
function intersect(start, end, wall) {
let dx = end.x - start.x;
let dy = end.y - start.y;
let wallX = wall.x2 - wall.x1;
let wallY = wall.y2 - wall.y1;
// The lines are parallel
let denominator = dx * wallY - dy * wallX;
if (denominator == 0) {
return null;
}
let startX = wall.x1 - start.x;
let startY = wall.y1 - start.y;
let t = (startX * wallY - startY * wallX) / denominator;
let u = (startX * dy - startY * dx) / denominator;
if (t < 0 || t > 1 || u < 0 || u > 1) {
return null;
}
return t;
}start and end are points with an x and a y. The function treats both as infinite lines, and works out where they meet. t tells you how far along the first line that is, from 0 at start to 1 at end, and u how far along the wall. Only when both are between 0 and 1 is the crossing on both segments. You don't need to follow every step of the math to use the function.
Now add an avoidWalls() method:
const feelerLength = 60;
// In the Vehicle class
avoidWalls(walls) {
let x = 0;
let y = 0;
// One feeler straight ahead, a shorter one on each side
let feelers = [
{angle: 0, length: feelerLength},
{angle: -0.6, length: feelerLength * 0.7},
{angle: 0.6, length: feelerLength * 0.7}
];
for (let feeler of feelers) {
let angle = this.angle + feeler.angle;
let tip = {
x: this.x + Math.cos(angle) * feeler.length,
y: this.y + Math.sin(angle) * feeler.length
};
for (let wall of walls) {
let t = intersect(this, tip, wall);
if (t == null) {
continue;
}
// The normal of the wall, with a length of 1
let wallX = wall.x2 - wall.x1;
let wallY = wall.y2 - wall.y1;
let wallLength = Math.hypot(wallX, wallY);
let normalX = -wallY / wallLength;
let normalY = wallX / wallLength;
// Point the normal toward the vehicle
let side =
(this.x - wall.x1) * normalX +
(this.y - wall.y1) * normalY;
if (side < 0) {
normalX = -normalX;
normalY = -normalY;
}
// How much of the feeler sticks through the wall
let depth = 1 - t;
x += normalX * depth;
y += normalY * depth;
}
}
// Steer away from the walls, as hard as it can
return this.steer(x, y);
}The side feelers point 0.6 radians, about 35 degrees, to the left and right, and they're 70% as long as the one in the middle. intersect(this, tip, wall) works because the vehicle itself has an x and a y, just like a point. When a feeler crosses a wall, depth is how much of the feeler is past the wall, from 0 to 1.
The normal of a wall is a direction at a right angle to it. A wall has two normals, one for each side, so the method picks the one that points toward the vehicle. That's the way out. The method adds up the normals of all the walls the feelers cross, each multiplied by its depth, so the wall a feeler goes deepest into counts the most. Then it steers that way with the full maxForce, because a vehicle that's about to hit a wall has no time to lose.
The vehicles in the room below wander around. Switch their feelers on and off. The feelers of the red vehicle turn red when they cross a wall:
Without feelers, the vehicles wander straight through the walls. With feelers, they turn away just before they reach a wall, and slide along a wall when they hit it at a shallow angle. Short feelers let a fast vehicle reach the wall before it can turn. Long feelers make it turn away from walls that are still far off, and it may not fit through a doorway anymore.
Follow a path
A car on a road, a train on a track and a guard on a patrol route all follow a path. A path can be a list of points, with lines between them. You could have the vehicle seek each point of the path in turn, but then it heads straight for every point and makes a sharp turn when it gets there. Reynolds' path following works differently. The path has a width, like a road, and the vehicle only steers when it's about to leave the road.
Each frame, the vehicle predicts where it will be lookAhead seconds from now, and finds the point on the path that's nearest to that future position. If the future position is still on the road, the vehicle just keeps going. If it isn't, the vehicle steers toward a point a bit further along the road. To find the nearest point on one segment of the path, use this function:
// The point between start and end that's closest to point
function getClosestPoint(point, start, end) {
let lineX = end.x - start.x;
let lineY = end.y - start.y;
let length = Math.hypot(lineX, lineY);
let directionX = lineX / length;
let directionY = lineY / length;
// How far along the line it is, from 0 to length
let along =
(point.x - start.x) * directionX +
(point.y - start.y) * directionY;
along = Math.min(Math.max(along, 0), length);
return {
x: start.x + directionX * along,
y: start.y + directionY * along,
directionX: directionX,
directionY: directionY
};
}The dot product gives along, just like in avoidObstacles(). Math.min() and Math.max() keep it between the start and the end of the segment. The function also returns the direction of the segment, so the vehicle knows which way is forward. Then add a followPath() method:
const lookAhead = 0.3;
const pathRadius = 20;
const pathAhead = 30;
// In the Vehicle class
followPath(path) {
// Where the vehicle will be, lookAhead seconds from now
let future = {
x: this.x + this.vx * lookAhead,
y: this.y + this.vy * lookAhead
};
// The point on the path nearest to that future position
let nearest = null;
let nearestDistance = 0;
for (let i = 0; i < path.length; i++) {
let start = path[i];
let end = path[(i + 1) % path.length];
let point = getClosestPoint(future, start, end);
let distance = Math.hypot(
future.x - point.x,
future.y - point.y
);
if (nearest == null || distance < nearestDistance) {
nearest = point;
nearestDistance = distance;
}
}
// Still on the path, and moving? Keep going at full speed
let isMoving = this.vx != 0 || this.vy != 0;
if (nearestDistance < pathRadius && isMoving) {
return this.steer(this.vx, this.vy);
}
// Otherwise, steer to a point further along the path
let targetX = nearest.x + nearest.directionX * pathAhead;
let targetY = nearest.y + nearest.directionY * pathAhead;
return this.seek(targetX, targetY);
}path is a list of points that form a loop, so after the last point, the path goes back to the first one. That's what (i + 1) % path.length does: for the last point, it gives 0. pathRadius is half the width of the road. pathAhead is how far ahead along the road the vehicle aims: the point it steers toward. On the road, steer() gets the vehicle's own velocity as the direction, so the vehicle speeds up to maxSpeed in the direction it's already going. A vehicle that isn't moving has no direction yet, so it steers toward the point farther along the road, even when it's on the road.
In the demo below, five cars drive around a road. Drag the white dots to change the road, or click Reset path to start over. The dashed line in front of the red car goes to its predicted position. When that position is off the road, a red dot shows the point the car steers to:
The cars don't all have the same maxSpeed. To keep them from driving through each other, they also use separation, which comes up later on this page. A fast car that catches up with a slow one gets pushed aside, and passes it when there's room. Make a corner very sharp, and the cars swing wide, like real cars that take a corner too fast.
For a route through a maze, the tutorial about pathfinding finds the shortest path first, and moves a character along it from point to point. The two work well together: pathfinding gives you the points, and path following makes the movement smooth.
Follow a flow field
A flow field is a grid in which every cell holds a direction, like the current in a river or the wind over a field. A vehicle looks up the cell it's about to enter, and steers in that direction. That's all there is to it, and it's cheap: a thousand vehicles can use the same field.
Store the field as a list of angles, one for each cell, row by row. The angle of a cell is at index row * columns + column in the list:
const cellSize = 50;
const columns = Math.ceil(canvasWidth / cellSize);
const rows = Math.ceil(canvasHeight / cellSize);
// In the Vehicle class
followField(field) {
// Where the vehicle will be, lookAhead seconds from now
let futureX = this.x + this.vx * lookAhead;
let futureY = this.y + this.vy * lookAhead;
// The cell at that position
let column = Math.floor(futureX / cellSize);
let row = Math.floor(futureY / cellSize);
// Stay inside the grid
column = Math.min(Math.max(column, 0), columns - 1);
row = Math.min(Math.max(row, 0), rows - 1);
let angle = field[row * columns + column];
return this.steer(Math.cos(angle), Math.sin(angle));
}canvasWidth and canvasHeight are the size of the canvas. Math.cos() and Math.sin() turn the angle of the cell into a direction for steer(). lookAhead is the same constant as in followPath(). The vehicle looks at the cell where it's going, so it starts to turn before it gets there.
You can fill the field however you like. This function makes a field that flows like water, with sine and cosine waves:
function createField() {
let angles = [];
// Random offsets, so every new field looks different
let offsetX = Math.random() * 2 * Math.PI;
let offsetY = Math.random() * 2 * Math.PI;
for (let row = 0; row < rows; row++) {
for (let column = 0; column < columns; column++) {
let wave =
Math.sin(column * 0.3 + offsetX) +
Math.cos(row * 0.4 + offsetY);
angles.push(wave * 1.5);
}
}
return angles;
}Each column and each row adds a little to the wave, so the angle changes slowly from one cell to the next. The wave goes from -2 to 2, and multiplying it by 1.5 lets the angles cover almost a full circle. That makes neighboring cells point in almost the same direction. The tutorial about smooth canvas animation shows what else you can do with Math.sin().
In the demo below, each gray arrow shows the direction of one cell, and the cell the red vehicle looks at is highlighted. Click New flow field for a different one:
The vehicles don't turn the moment they enter a new cell. maxForce limits how fast they can turn, so they follow the field in smooth curves. To lead every vehicle to the same goal, around walls, you build the field from the goal outward. The tutorial about pathfinding does that to guide a whole swarm.
Move as a group with separation, alignment and cohesion
The three rules of boids are steering behaviors too. Separation keeps a vehicle away from its neighbors, alignment makes it go in the same direction as its neighbors, and cohesion pulls it toward the middle of the group. Together, they make a flock. The tutorial about flocking with boids covers them one by one, with a demo for each rule. It also shows you how to find the neighbors of each boid quickly, even in a flock of thousands.
The next behavior needs separation, so here's the method. separate() steers the vehicle away from every other vehicle that's closer than separationDistance:
const separationDistance = 25;
// In the Vehicle class
separate(others) {
let x = 0;
let y = 0;
for (let other of others) {
let dx = this.x - other.x;
let dy = this.y - other.y;
let distance = Math.hypot(dx, dy);
if (distance > 0 && distance < separationDistance) {
// Closer vehicles count more
x += dx / distance / distance;
y += dy / distance / distance;
}
}
return this.steer(x, y);
}others is a list of vehicles, and it can include the vehicle itself. The distance to itself is 0, so the method skips it. The first division gives a direction of length 1, and the second makes a closer vehicle count more, so the vehicle mostly steers away from its nearest neighbors.
Follow a leader
Ducklings follow their mother, soldiers follow their captain, and in a role-playing game, the party follows the player. With leader following, each follower arrives at a point just behind the leader. Separation keeps the followers from piling up at that point.
There's one more problem. When the leader turns around, it runs straight into its own followers. So a follower that's in front of the leader first gets out of the way, by evading the leader:
const followDistance = 20;
// In the Vehicle class
followLeader(leader) {
// The direction the leader faces
let headingX = Math.cos(leader.angle);
let headingY = Math.sin(leader.angle);
// In front of the leader? Get out of the way
let aheadX = leader.x + headingX * followDistance;
let aheadY = leader.y + headingY * followDistance;
let dx = this.x - aheadX;
let dy = this.y - aheadY;
if (Math.hypot(dx, dy) < followDistance) {
return this.evade(leader);
}
// Otherwise, arrive at a point just behind the leader
let behindX = leader.x - headingX * followDistance;
let behindY = leader.y - headingY * followDistance;
return this.arrive(behindX, behindY, followDistance);
}leader is a Vehicle. The point the follower arrives at is followDistance behind it. The area the follower has to stay out of is a circle in front of the leader, with a radius of followDistance. The follower only starts to slow down when it's within followDistance of the point behind the leader, not within slowRadius, so it keeps up with the leader instead of crawling after it. followDistance is less than the braking distance from the arrive section, but a follower rarely has to stop from full speed: the point it follows moves along with the leader.
Keep the followers in a list called followers. In the game loop, every follower follows the leader and keeps away from the others. Separation gets a weight of 1.5, a bit more than following, so the followers don't pile up:
for (let follower of followers) {
follower.applyForce(follower.followLeader(leader));
follower.applyForce(follower.separate(followers), 1.5);
}For a row of ducklings, each follower follows the one in front of it instead:
for (let i = 0; i < followers.length; i++) {
let ahead = i == 0 ? leader : followers[i - 1];
followers[i].applyForce(followers[i].followLeader(ahead));
followers[i].applyForce(followers[i].separate(followers), 1.5);
}Move your mouse over the pond below, or touch it, and the mother duck swims toward your mouse or finger with the arrive behavior. If you don't, she wanders around. With Behind the leader, the dashed circle in front of her is the area the ducklings stay out of. Switch between Behind the leader and In single file:
With Behind the leader, the ducklings crowd together behind their mother, and scatter when she turns toward them. In single file, they form a neat row that follows her path, because each duckling follows the one in front of it.
Combine steering behaviors
Most characters use more than one behavior at a time. A guard wanders around, stays away from walls and runs from the player. The easiest way to combine behaviors is a weighted sum: add up all the forces, each multiplied by a weight. That's what applyForce() does, and it's how the boids in the flocking tutorial combine their three rules.
The trouble is that the forces can work against each other. When the player chases the guard into a wall, flee pushes the guard toward the wall, and the feelers push it back. If flee has the bigger weight, the guard runs right through the wall. If the walls have the bigger weight, the guard can hardly flee when it's near a wall. And two forces that cancel each other out can leave a character standing still.
The other option is to combine the forces by priority. The most important behavior gets the first share of maxForce, the next one gets what's left, and so on, until maxForce is used up. Add an applyPriority() method that takes a list of forces, with the most important one first:
// In the Vehicle class
applyPriority(forces) {
let left = this.maxForce;
for (let force of forces) {
let size = Math.hypot(force.x, force.y);
if (size == 0) {
continue;
}
// Not enough left? Use what's left, and stop
if (size > left) {
this.applyForce(force, left / size);
return;
}
this.applyForce(force);
left -= size;
}
}left is how much of maxForce remains. A force that's bigger than that gets scaled down to fit, and the forces after it get nothing in that frame. A force of 0, like flee when the player is far away, doesn't use anything. So when a feeler crosses a wall, avoidWalls() uses up all of maxForce, and the guard only flees again once it has turned away from the wall.
For the guard, avoiding walls comes first, then fleeing from the player, and then wandering around. pointer is the position of the mouse or finger on the canvas, and the example code at the end of this page shows how to keep track of it:
guard.applyPriority([
guard.avoidWalls(walls),
guard.flee(pointer.x, pointer.y),
guard.wander(secondsPassed)
]);Move your mouse over the canvas below, or touch it, to chase the guard into a wall. Then switch between By weight and By priority. The code below the canvas shows how the forces are combined:
guard.applyForce(guard.avoidWalls(walls), 1);
guard.applyForce(guard.flee(pointer.x, pointer.y), 3);
guard.applyForce(guard.wander(secondsPassed), 1);With By weight, flee has a weight of 3 and the walls only 1, so the guard runs straight through a wall when you chase it there. The counter in the corner shows how often that happens. With By priority, the walls always come first: the guard turns away from a wall before it flees again, and slides along the wall to get away from you.
Priority isn't always better. With a weighted sum, every behavior has a say all the time, and that's what you want in a flock. A good mix is to use priority for the behaviors that keep a character safe, like avoiding walls and obstacles, and a weighted sum for the rest. Switching between whole sets of behaviors, like patrolling and chasing, is a job for the layer above steering, such as the state machine in the tutorial about game states.
Common questions about steering behaviors
Who invented steering behaviors?
Craig Reynolds, the computer graphics researcher who also came up with boids. He presented steering behaviors at the Game Developers Conference in 1999, in a paper called Steering Behaviors For Autonomous Characters. The paper is still on his website, with a diagram for each behavior.
What's the difference between steering behaviors and pathfinding?
Pathfinding decides which route to take, and steering decides how to move. Pathfinding looks at the whole map to find a way around walls, so it takes more time to run. Steering only looks at what's right around the character, every frame, and that's cheap. In a game, you often use both: pathfinding for the route, and path following, separation and obstacle avoidance to move along it.
What's the difference between seek and arrive?
Seek always steers toward the target at full speed, so the character shoots past a target that stands still. Arrive does the same far from the target, but slows down within slowRadius, so the character stops at the target. Use seek for a target that keeps moving, and arrive for a spot the character has to reach.
Why does my character jitter or wobble?
Usually because two forces fight each other, and each frame a different one wins. Combine them by priority, or give one of them a smaller weight. A character can also wobble when reactionTime is too long, because it turns too slowly and keeps overshooting where it wants to go. And make sure you multiply the acceleration and the velocity by secondsPassed, like update() does.
Why does my character get stuck between two obstacles?
When two obstacles push it in opposite directions, the forces cancel each other out. Obstacle avoidance by looking ahead only reacts to the nearest obstacle in front of the character, which helps a lot. If the gap is too narrow for the character, it can't get through at all: make the gap wider, or let pathfinding find a way around.
How do I make my character face the direction it's moving?
Math.atan2(vy, vx) gives you the angle of the velocity, and you rotate the drawing by that angle, like draw() in the example code. When the character stops, the velocity is close to 0, and the angle can jump around. So only change the angle while the character is moving, like update() does.
Can I use steering behaviors in Unity or Godot?
Yes. The behaviors are just math with positions and velocities, so the same approach works in any engine. In Unity or Godot, you'd use the engine's vector type instead of x and y, and let the engine move the character. Both engines also have navigation agents that find a route and avoid each other for you.
Example code: steering behaviors
Here's an example page that puts the basics from this tutorial together in a single HTML file: the Vehicle class with every behavior from this page, and a small scene with a button for each behavior. The red vehicle follows your mouse, and the blue vehicles use the behavior you pick, while they avoid the walls and obstacles, which take priority. Paste the code below into an HTML file and open it in your browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Steering Behaviors Tutorial | Spicy Yoghurt</title>
<style>
#canvas {
width: 750px;
height: 400px;
border: 1px solid lightgray;
touch-action: none;
}
</style>
</head>
<body>
<h1>Steering behaviors tutorial by Spicy Yoghurt</h1>
<div id="buttons"></div>
<canvas id="canvas" width="750" height="400">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
'use strict';
// The size of the canvas
const canvasWidth = 750;
const canvasHeight = 400;
// How fast a vehicle reacts, in seconds
const reactionTime = 0.1;
// Settings for the behaviors
const fleeRadius = 150;
const slowRadius = 120;
const maxPredictTime = 1;
const wanderDistance = 60;
const wanderRadius = 30;
const wanderChange = 4;
const avoidLength = 100;
const vehicleRadius = 10;
const feelerLength = 60;
const lookAhead = 0.3;
const pathRadius = 20;
const pathAhead = 30;
const followDistance = 20;
const separationDistance = 25;
// The flow field
const cellSize = 50;
const columns = Math.ceil(canvasWidth / cellSize);
const rows = Math.ceil(canvasHeight / cellSize);
const behaviors = [
'Seek', 'Flee', 'Arrive', 'Pursue', 'Evade', 'Wander',
'Follow path', 'Follow flow field', 'Follow leader'
];
let canvas;
let context;
let behavior = 'Seek';
let leader;
let vehicles = [];
let field = [];
let pointer = {x: 0, y: 0, isActive: false};
let oldTimeStamp = 0;
let obstacles = [
{x: 250, y: 170, radius: 35},
{x: 500, y: 210, radius: 45},
{x: 380, y: 260, radius: 22}
];
// The walls run along the edges of the canvas
let walls = [
{x1: 10, y1: 10, x2: 740, y2: 10},
{x1: 740, y1: 10, x2: 740, y2: 390},
{x1: 740, y1: 390, x2: 10, y2: 390},
{x1: 10, y1: 390, x2: 10, y2: 10}
];
// A loop around the obstacles
let path = [
{x: 100, y: 80},
{x: 650, y: 80},
{x: 650, y: 320},
{x: 100, y: 320}
];
class Vehicle {
constructor(x, y, maxSpeed, maxForce) {
this.x = x;
this.y = y;
this.vx = 0;
this.vy = 0;
this.ax = 0;
this.ay = 0;
this.maxSpeed = maxSpeed;
this.maxForce = maxForce;
this.angle = 0;
this.wanderAngle = 0;
}
// Steer in the direction (x, y) at the given speed
steer(x, y, speed = this.maxSpeed) {
let length = Math.hypot(x, y);
if (length == 0) {
return {x: 0, y: 0};
}
// The desired velocity: the direction at the given speed
let desiredX = x / length * speed;
let desiredY = y / length * speed;
// The difference from the current velocity
let steerX = (desiredX - this.vx) / reactionTime;
let steerY = (desiredY - this.vy) / reactionTime;
let force = Math.hypot(steerX, steerY);
if (force > this.maxForce) {
steerX *= this.maxForce / force;
steerY *= this.maxForce / force;
}
return {x: steerX, y: steerY};
}
applyForce(force, weight = 1) {
this.ax += force.x * weight;
this.ay += force.y * weight;
}
// Add the forces in order, until maxForce is used up
applyPriority(forces) {
let left = this.maxForce;
for (let force of forces) {
let size = Math.hypot(force.x, force.y);
if (size == 0) {
continue;
}
// Not enough left? Use what's left, and stop
if (size > left) {
this.applyForce(force, left / size);
return;
}
this.applyForce(force);
left -= size;
}
}
update(secondsPassed) {
this.vx += this.ax * secondsPassed;
this.vy += this.ay * secondsPassed;
this.ax = 0;
this.ay = 0;
// Never move faster than maxSpeed
let speed = Math.hypot(this.vx, this.vy);
if (speed > this.maxSpeed) {
this.vx *= this.maxSpeed / speed;
this.vy *= this.maxSpeed / speed;
}
this.x += this.vx * secondsPassed;
this.y += this.vy * secondsPassed;
// Face the way it's moving, but not when it stands still
if (speed > 1) {
this.angle = Math.atan2(this.vy, this.vx);
}
}
seek(x, y) {
return this.steer(x - this.x, y - this.y);
}
flee(x, y) {
let dx = this.x - x;
let dy = this.y - y;
if (Math.hypot(dx, dy) > fleeRadius) {
return {x: 0, y: 0};
}
return this.steer(dx, dy);
}
arrive(x, y, radius = slowRadius) {
let dx = x - this.x;
let dy = y - this.y;
let distance = Math.hypot(dx, dy);
// Within the radius, slow down to 0 at the target
let speed = this.maxSpeed;
if (distance < radius) {
speed = this.maxSpeed * distance / radius;
}
return this.steer(dx, dy, speed);
}
// Where the target will be, a moment from now
predict(target) {
let dx = target.x - this.x;
let dy = target.y - this.y;
// Roughly the time it takes to get there
let time = Math.hypot(dx, dy) / this.maxSpeed;
time = Math.min(time, maxPredictTime);
return {
x: target.x + target.vx * time,
y: target.y + target.vy * time
};
}
pursue(target) {
let future = this.predict(target);
return this.seek(future.x, future.y);
}
evade(target) {
let future = this.predict(target);
return this.flee(future.x, future.y);
}
wander(secondsPassed) {
// Move the point a little bit along the circle
let change = Math.random() * 2 - 1;
this.wanderAngle += change * wanderChange * secondsPassed;
// The center of the circle, in front of the vehicle
let headingX = Math.cos(this.angle);
let headingY = Math.sin(this.angle);
let centerX = this.x + headingX * wanderDistance;
let centerY = this.y + headingY * wanderDistance;
// The point on the circle
let angle = this.angle + this.wanderAngle;
let targetX = centerX + Math.cos(angle) * wanderRadius;
let targetY = centerY + Math.sin(angle) * wanderRadius;
return this.seek(targetX, targetY);
}
avoidObstacles(obstacles) {
let speed = Math.hypot(this.vx, this.vy);
if (speed == 0) {
return {x: 0, y: 0};
}
// The direction it's moving in, with a length of 1
let forwardX = this.vx / speed;
let forwardY = this.vy / speed;
// Look further ahead when it moves faster
let ahead = avoidLength * speed / this.maxSpeed;
let nearest = null;
let nearestAlong = 0;
let nearestSide = 0;
for (let obstacle of obstacles) {
let dx = obstacle.x - this.x;
let dy = obstacle.y - this.y;
// How far ahead it is, and how far to the side
let along = dx * forwardX + dy * forwardY;
let side = dx * forwardY - dy * forwardX;
// Skip obstacles behind the vehicle or too far ahead
if (along < 0 || along > ahead + obstacle.radius) {
continue;
}
// Skip obstacles that the vehicle will miss
let clearance = obstacle.radius + vehicleRadius;
if (Math.abs(side) > clearance) {
continue;
}
if (nearest == null || along < nearestAlong) {
nearest = obstacle;
nearestAlong = along;
nearestSide = side;
}
}
if (nearest == null) {
return {x: 0, y: 0};
}
// Steer right when the obstacle is on the left, and left
// when it's on the right
let turn = nearestSide > 0 ? 1 : -1;
let force = this.steer(-forwardY * turn, forwardX * turn);
// Steer harder when the obstacle is closer
let range = ahead + nearest.radius;
let strength = 1 - nearestAlong / range;
return {x: force.x * strength, y: force.y * strength};
}
avoidWalls(walls) {
let x = 0;
let y = 0;
// One feeler straight ahead, a shorter one on each side
let feelers = [
{angle: 0, length: feelerLength},
{angle: -0.6, length: feelerLength * 0.7},
{angle: 0.6, length: feelerLength * 0.7}
];
for (let feeler of feelers) {
let angle = this.angle + feeler.angle;
let tip = {
x: this.x + Math.cos(angle) * feeler.length,
y: this.y + Math.sin(angle) * feeler.length
};
for (let wall of walls) {
let t = intersect(this, tip, wall);
if (t == null) {
continue;
}
// The normal of the wall, with a length of 1
let wallX = wall.x2 - wall.x1;
let wallY = wall.y2 - wall.y1;
let wallLength = Math.hypot(wallX, wallY);
let normalX = -wallY / wallLength;
let normalY = wallX / wallLength;
// Point the normal toward the vehicle
let side =
(this.x - wall.x1) * normalX +
(this.y - wall.y1) * normalY;
if (side < 0) {
normalX = -normalX;
normalY = -normalY;
}
// How much of the feeler sticks through the wall
let depth = 1 - t;
x += normalX * depth;
y += normalY * depth;
}
}
// Steer away from the walls, as hard as it can
return this.steer(x, y);
}
followPath(path) {
// Where the vehicle will be, lookAhead seconds from now
let future = {
x: this.x + this.vx * lookAhead,
y: this.y + this.vy * lookAhead
};
// The point on the path nearest to that future position
let nearest = null;
let nearestDistance = 0;
for (let i = 0; i < path.length; i++) {
let start = path[i];
let end = path[(i + 1) % path.length];
let point = getClosestPoint(future, start, end);
let distance = Math.hypot(
future.x - point.x,
future.y - point.y
);
if (nearest == null || distance < nearestDistance) {
nearest = point;
nearestDistance = distance;
}
}
// Still on the path, and moving? Keep going at full speed
let isMoving = this.vx != 0 || this.vy != 0;
if (nearestDistance < pathRadius && isMoving) {
return this.steer(this.vx, this.vy);
}
// Otherwise, steer to a point further along the path
let targetX = nearest.x + nearest.directionX * pathAhead;
let targetY = nearest.y + nearest.directionY * pathAhead;
return this.seek(targetX, targetY);
}
followField(field) {
// Where the vehicle will be, lookAhead seconds from now
let futureX = this.x + this.vx * lookAhead;
let futureY = this.y + this.vy * lookAhead;
// The cell at that position
let column = Math.floor(futureX / cellSize);
let row = Math.floor(futureY / cellSize);
// Stay inside the grid
column = Math.min(Math.max(column, 0), columns - 1);
row = Math.min(Math.max(row, 0), rows - 1);
let angle = field[row * columns + column];
return this.steer(Math.cos(angle), Math.sin(angle));
}
separate(others) {
let x = 0;
let y = 0;
for (let other of others) {
let dx = this.x - other.x;
let dy = this.y - other.y;
let distance = Math.hypot(dx, dy);
if (distance > 0 && distance < separationDistance) {
// Closer vehicles count more
x += dx / distance / distance;
y += dy / distance / distance;
}
}
return this.steer(x, y);
}
followLeader(leader) {
// The direction the leader faces
let headingX = Math.cos(leader.angle);
let headingY = Math.sin(leader.angle);
// In front of the leader? Get out of the way
let aheadX = leader.x + headingX * followDistance;
let aheadY = leader.y + headingY * followDistance;
let dx = this.x - aheadX;
let dy = this.y - aheadY;
if (Math.hypot(dx, dy) < followDistance) {
return this.evade(leader);
}
// Otherwise, arrive at a point just behind the leader
let behindX = leader.x - headingX * followDistance;
let behindY = leader.y - headingY * followDistance;
return this.arrive(behindX, behindY, followDistance);
}
draw(color) {
context.save();
context.translate(this.x, this.y);
context.rotate(this.angle);
context.beginPath();
context.moveTo(9, 0);
context.lineTo(-7, 6);
context.lineTo(-7, -6);
context.closePath();
context.fillStyle = color;
context.fill();
context.restore();
}
}
// Where the line from start to end crosses the wall, as a number
// from 0 at start to 1 at end, or null if they don't cross
function intersect(start, end, wall) {
let dx = end.x - start.x;
let dy = end.y - start.y;
let wallX = wall.x2 - wall.x1;
let wallY = wall.y2 - wall.y1;
// The lines are parallel
let denominator = dx * wallY - dy * wallX;
if (denominator == 0) {
return null;
}
let startX = wall.x1 - start.x;
let startY = wall.y1 - start.y;
let t = (startX * wallY - startY * wallX) / denominator;
let u = (startX * dy - startY * dx) / denominator;
if (t < 0 || t > 1 || u < 0 || u > 1) {
return null;
}
return t;
}
// The point between start and end that's closest to point
function getClosestPoint(point, start, end) {
let lineX = end.x - start.x;
let lineY = end.y - start.y;
let length = Math.hypot(lineX, lineY);
let directionX = lineX / length;
let directionY = lineY / length;
// How far along the line it is, from 0 to length
let along =
(point.x - start.x) * directionX +
(point.y - start.y) * directionY;
along = Math.min(Math.max(along, 0), length);
return {
x: start.x + directionX * along,
y: start.y + directionY * along,
directionX: directionX,
directionY: directionY
};
}
function createField() {
let angles = [];
// Random offsets, so every new field looks different
let offsetX = Math.random() * 2 * Math.PI;
let offsetY = Math.random() * 2 * Math.PI;
for (let row = 0; row < rows; row++) {
for (let column = 0; column < columns; column++) {
let wave =
Math.sin(column * 0.3 + offsetX) +
Math.cos(row * 0.4 + offsetY);
angles.push(wave * 1.5);
}
}
return angles;
}
window.onload = init;
function init() {
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
addButtons();
addPointerEvents();
field = createField();
leader = new Vehicle(375, 120, 100, 200);
for (let i = 0; i < 8; i++) {
vehicles.push(new Vehicle(
60 + Math.random() * 630,
60 + Math.random() * 280,
120,
200
));
}
window.requestAnimationFrame(gameLoop);
}
function addButtons() {
let buttons = document.getElementById('buttons');
for (let name of behaviors) {
let button = document.createElement('button');
button.textContent = name;
button.addEventListener('click', function () {
behavior = name;
});
buttons.appendChild(button);
}
}
function addPointerEvents() {
canvas.addEventListener('pointermove', movePointer);
canvas.addEventListener('pointerdown', movePointer);
canvas.addEventListener('pointerleave', function () {
pointer.isActive = false;
});
canvas.addEventListener('pointerup', function (event) {
// The leader wanders again when you lift your finger
if (event.pointerType != 'mouse') {
pointer.isActive = false;
}
});
}
function movePointer(event) {
// The position on the canvas, even when it's scaled
let rect = canvas.getBoundingClientRect();
let scaleX = canvasWidth / rect.width;
let scaleY = canvasHeight / rect.height;
pointer.x = (event.clientX - rect.left) * scaleX;
pointer.y = (event.clientY - rect.top) * scaleY;
pointer.isActive = true;
}
// The force of the chosen behavior, for the vehicle at index i
function getForce(vehicle, i, secondsPassed) {
if (behavior == 'Seek') {
return vehicle.seek(leader.x, leader.y);
} else if (behavior == 'Flee') {
return vehicle.flee(leader.x, leader.y);
} else if (behavior == 'Arrive') {
return vehicle.arrive(leader.x, leader.y);
} else if (behavior == 'Pursue') {
return vehicle.pursue(leader);
} else if (behavior == 'Evade') {
return vehicle.evade(leader);
} else if (behavior == 'Wander') {
return vehicle.wander(secondsPassed);
} else if (behavior == 'Follow path') {
return vehicle.followPath(path);
} else if (behavior == 'Follow flow field') {
return vehicle.followField(field);
}
// Follow the leader in single file, and keep some distance
let ahead = i == 0 ? leader : vehicles[i - 1];
let follow = vehicle.followLeader(ahead);
let separation = vehicle.separate(vehicles);
return {
x: follow.x + separation.x * 1.5,
y: follow.y + separation.y * 1.5
};
}
function gameLoop(timeStamp) {
let secondsPassed = (timeStamp - oldTimeStamp) / 1000;
oldTimeStamp = timeStamp;
// Don't jump ahead after the tab was hidden
secondsPassed = Math.min(secondsPassed, 0.1);
// The leader follows the mouse, or wanders around
let goal = pointer.isActive
? leader.arrive(pointer.x, pointer.y)
: leader.wander(secondsPassed);
leader.applyPriority([
leader.avoidWalls(walls),
leader.avoidObstacles(obstacles),
goal
]);
for (let i = 0; i < vehicles.length; i++) {
let vehicle = vehicles[i];
vehicle.applyPriority([
vehicle.avoidWalls(walls),
vehicle.avoidObstacles(obstacles),
getForce(vehicle, i, secondsPassed)
]);
}
// First work out every force, then move every vehicle
leader.update(secondsPassed);
for (let vehicle of vehicles) {
vehicle.update(secondsPassed);
}
draw();
window.requestAnimationFrame(gameLoop);
}
function draw() {
context.clearRect(0, 0, canvasWidth, canvasHeight);
if (behavior == 'Follow path') {
drawPath();
} else if (behavior == 'Follow flow field') {
drawField();
}
context.strokeStyle = '#303030';
context.lineWidth = 4;
for (let wall of walls) {
context.beginPath();
context.moveTo(wall.x1, wall.y1);
context.lineTo(wall.x2, wall.y2);
context.stroke();
}
context.fillStyle = '#303030';
for (let obstacle of obstacles) {
context.beginPath();
context.arc(
obstacle.x, obstacle.y, obstacle.radius,
0, 2 * Math.PI
);
context.fill();
}
for (let vehicle of vehicles) {
vehicle.draw('#0099b0');
}
leader.draw('#ff8080');
context.fillStyle = 'black';
context.font = '18px Arial';
context.fillText('Behavior: ' + behavior, 25, 40);
}
function drawPath() {
context.strokeStyle = 'lightgray';
context.lineWidth = pathRadius * 2;
context.lineJoin = 'round';
context.beginPath();
for (let point of path) {
context.lineTo(point.x, point.y);
}
context.closePath();
context.stroke();
}
function drawField() {
context.strokeStyle = 'lightgray';
context.lineWidth = 2;
for (let row = 0; row < rows; row++) {
for (let column = 0; column < columns; column++) {
// A short line through the middle of the cell
let angle = field[row * columns + column];
let x = (column + 0.5) * cellSize;
let y = (row + 0.5) * cellSize;
let dx = Math.cos(angle) * cellSize * 0.3;
let dy = Math.sin(angle) * cellSize * 0.3;
context.beginPath();
context.moveTo(x - dx, y - dy);
context.lineTo(x + dx, y + dy);
context.stroke();
}
}
}
</script>
</body>
</html>Conclusion
Steering behaviors make your characters move on their own, one small force at a time. Seek, flee and arrive move a vehicle toward or away from a target, and pursue and evade predict where another character is going. Wander makes a vehicle roam around, and obstacle avoidance, feelers, path following and flow fields keep it on track. Leader following keeps a group together, and priorities decide what matters most.
Steering is only the middle layer. For the layer above it, deciding when a guard patrols and when it chases the player, take a look at the tutorial about game states. And for a route through a maze, try the tutorial about pathfinding.
That's all for now. If you have any questions, feel free to ask them in the comment section. You can download the example code here.
Comments
Thanks! We've received your comment. We check every comment by hand before it appears, so this can take a few days.

No comments yet. Be the first to leave one!