Open this sketch in P5 Web Editor →
Click to watch obstacles clear the path before the main movement begins.
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.
To create "before" relationships in programming:
let isClearing = false;
obstacle.hasCleared
for (let item of array)
- gives you each item directlyfor (let i = 0; i < array.length; i++)
- uses index numbers${cleared}/4 cleared
if (allCleared)
isClearing = false; isMoving = true;
obstacles.push({x: startX, y: startY, hasCleared: false});
let allCleared = true;
for (let obstacle of obstacles) {
if (!obstacle.hasCleared) allCleared = false;
}
if (allCleared) {
isClearing = false;
isMoving = true; // Main action starts
}
for (let obstacle of obstacles) {
if (obstacle.hasCleared) cleared++;
}
text(`Clearing path (${cleared}/4 cleared)`, x, y);
// 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
}
lerp(start, stop, amount)
- Interpolates between two valuesstart
- Current positionstop
- Target positionamount
- How much to move (0.1 = move 10% closer each frame)