Motion: Steering

Use vectors to steer an agent toward a target (the mouse).

Example 1: Seek Mouse

Code

let pos, vel;

function setup() {
  createCanvas(400, 400);
  pos = createVector(width / 2, height / 2);
  vel = createVector(0, 0);
}

function draw() {
  background(250);
  const target = createVector(mouseX, mouseY);
  const desired = p5.Vector.sub(target, pos).setMag(3);
  const steer = p5.Vector.sub(desired, vel).limit(0.15);

  vel.add(steer).limit(4);
  pos.add(vel);

  fill(255, 45, 140);
  noStroke();
  circle(pos.x, pos.y, 26);
}

Try this: Lower maxForce to make turns smoother and wider.

Open sketch in new tab

Example 2: Arrive Behavior

Code

let p, v;

function setup() {
  createCanvas(400, 400);
  p = createVector(60, 60);
  v = createVector(0, 0);
}

function draw() {
  background(255);
  const t = createVector(mouseX, mouseY);
  const desired = p5.Vector.sub(t, p);
  const d = desired.mag();
  const speed = d < 120 ? map(d, 0, 120, 0, 4) : 4;
  desired.setMag(speed);

  const steer = p5.Vector.sub(desired, v).limit(0.2);
  v.add(steer);
  p.add(v);

  fill(255, 45, 140);
  circle(p.x, p.y, 22);
  stroke(40, 40, 50, 120);
  line(p.x, p.y, mouseX, mouseY);
}

Try this: Change slow radius for snappier or softer arrival.

Open sketch in new tab

Resources