Try It

Click anywhere to set a target and watch the circle move toward it.

Concept

TOWARD means moving in the direction of something, approaching a target. This involves calculating direction vectors and moving an object closer to a destination over time.

Translation Strategy

To create "toward" relationships on screen:

Key P5.js Methods

Vector Mathematics:
• Calculate direction: dx = targetX - currentX, dy = targetY - currentY
atan2(dy, dx) - Calculate angle toward target
cos(angle) and sin(angle) - Convert angle to movement

Distance and Movement:
dist(x1, y1, x2, y2) - Calculate distance to target
lerp(start, stop, amount) - Smooth movement toward target

Drawing Elements:
ellipse(x, y, width, height) - Draw moving objects
line(x1, y1, x2, y2) - Draw direction indicators
Custom arrow drawing - Show direction visually

Animation:
• Update position each frame in draw() function
• Use speed variables to control movement rate

Mouse Interaction:
mousePressed() - Set new target when mouse is clicked
mouseX and mouseY - Get target coordinates

Code Structure

Basic Pattern for "Toward":

1. Define moving object and target: Set up initial positions
let movingObject = {x: 100, y: 100, speed: 2};
let target = {x: 300, y: 200};

2. Calculate direction: Find vector toward target
let dx = target.x - movingObject.x;
let dy = target.y - movingObject.y;
let distance = dist(movingObject.x, movingObject.y, target.x, target.y);

3. Move toward target: Update position each frame
if (distance > movingObject.speed) {
  let moveX = (dx / distance) * movingObject.speed;
  let moveY = (dy / distance) * movingObject.speed;
  movingObject.x += moveX;
  movingObject.y += moveY;
}