Movement & direction
Toward
Click or tap to set a target. The circle moves step by step toward that point each frame.
Try it — drag, click, or tap inside the figure.
Open in p5 Web Editor Fork and experiment with this sketchConcept
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
Code pattern
Code pattern
1. Store mover and target
2. Find direction
3. Step toward target
4. Set target on click
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;