Try It

Click to watch obstacles clear the path before the main movement begins.

Concept

BEFORE means occurring earlier than a reference event. This shows obstacles moving out of the way before a main movement can begin, demonstrating that one action must complete before another can start.

Translation Strategy

To create "before" relationships in programming:

Key P5.js Methods

State Tracking:
• Boolean flags: let isClearing = false;
Arrays - Store multiple objects to check
• Object properties: obstacle.hasCleared

Loop Types - Working with Arrays:
for...of loop: for (let item of array) - gives you each item directly
Traditional for loop: for (let i = 0; i < array.length; i++) - uses index numbers
• Use for...of when you just need to work with each item
• Use traditional for when you need the position/index number

Movement & Animation:
lerp(start, stop, amount) - Smooth interpolation between values
dist() - Check if objects reached targets
random() - Generate scatter positions

Visual Feedback:
fill(r, g, b) - Color changes for states
• Progress counters: ${cleared}/4 cleared
• Trail visualization with map()

Conditional Logic:
• Check all prerequisites: if (allCleared)
• State transitions: isClearing = false; isMoving = true;

Code Structure

Basic Pattern for "Before":

1. Create obstacles: Objects that must move before main action
obstacles.push({x: startX, y: startY, hasCleared: false});

2. Check prerequisites using for...of loop:
let allCleared = true;
for (let obstacle of obstacles) {
  if (!obstacle.hasCleared) allCleared = false;
}

3. Progress when ready: Start main action only after setup
if (allCleared) {
  isClearing = false;
  isMoving = true; // Main action starts
}

4. Visual feedback with for...of loop:
for (let obstacle of obstacles) {
  if (obstacle.hasCleared) cleared++;
}
text(`Clearing path (${cleared}/4 cleared)`, x, y);

Loop Comparison Example:
// for...of: easier to read, gives you the item directly
for (let obstacle of obstacles) {
  obstacle.x = lerp(obstacle.x, obstacle.targetX, 0.1);
}

// Traditional for: when you need the index position
for (let i = 0; i < obstacles.length; i++) {
  obstacles[i].x = 120 + (i * 60); // Position based on index
}

Understanding lerp():
lerp(start, stop, amount) - Interpolates between two values
start - Current position
stop - Target position
amount - How much to move (0.1 = move 10% closer each frame)
• Creates smooth, eased movement that slows down as it approaches the target