Movement & direction

Toward

Click or tap to set a target. The circle moves step by step toward that point each frame.

Fig. 1 Direction vector — the mover advances toward the target each frame

Try it — drag, click, or tap inside the figure.

Open in p5 Web Editor Fork and experiment with this sketch

Concept

TOWARD means moving in the direction of something. Compute the vector from the object to the target and advance along it over time.

Translation strategy

Ways to express toward in a sketch:

  • Direction vector: Find Δx and Δy from current position to target
  • Step each frame: Move a fixed distance per draw() cycle
  • Stop at arrival: Halt when distance is less than one step
Key p5.js methods
Key methods

Vector math
dist() — remaining distance
atan2(), cos(), sin() — direction
lerp() — optional eased motion

Drawing
ellipse(), line() — object and direction guide

Pointer input
mousePressed() — start motion or set a target
mouseX, mouseY — click position
Code pattern
Code pattern

1. Store mover and target
let mover = { x: 100, y: 100, speed: 2 };
let target = { x: 300, y: 200 };

2. Find direction
let dx = target.x - mover.x;
let dy = target.y - mover.y;
let d = dist(mover.x, mover.y, target.x, target.y);

3. Step toward target
if (d > mover.speed) {
  mover.x += (dx / d) * mover.speed;
  mover.y += (dy / d) * mover.speed;
}

4. Set target on click
target.x = mouseX; target.y = mouseY;