Creative Coding · Session c13
Collisions & Score
Turn “these two things overlap” into a game event.
Imagine guiding a pony around a paddock to collect apples. Your eyes can tell when the pony touches an apple, but code needs a precise test. For two round objects, ask whether the distance between their centres is smaller than their combined reach.
Picture the collision test
🐴
🍎
distance < 28 pixels
The centres are close enough, so the circles overlap: collect the apple and add 1 to the score.
In p5.js,
dist(x1, y1, x2, y2) measures that centre-to-centre distance.
Live sketch — paddock collector
Move your finger or mouse around the paddock. Collect all eight apples.
let apples = [];
let score = 0;
function setup() {
createCanvas(420, 280);
for (let i = 0; i < 8; i++) {
apples.push({ x: random(30, 390), y: random(55, 250) });
}
}
function draw() {
background('#bde0a8');
let horseX = constrain(mouseX, 20, width - 20);
let horseY = constrain(mouseY, 45, height - 20);
for (let i = apples.length - 1; i >= 0; i--) {
let a = apples[i];
fill('#e63946');
circle(a.x, a.y, 22);
let gap = dist(horseX, horseY, a.x, a.y);
if (gap < 28) {
apples.splice(i, 1);
score += 1;
}
}
fill('#7c3aed');
circle(horseX, horseY, 34);
fill(20);
text('Score: ' + score, 15, 27);
}
Why loop backwards?
splice(i, 1) removes the item at index i. Removing an item shifts everything after it one place to the left. A forward loop can then skip the next apple. Starting at the final index and moving backward keeps every unvisited index stable.
Quick check — which test is correct?
The pony is at (100, 100) and an apple is at (120, 100). The collision limit is 28 pixels. Is it collected?
Answer: Yes. The centres are 20 pixels apart, and 20 < 28. (The dollar signs are coordinates here; the program uses dist(100, 100, 120, 100).)
Challenges — tune the game rules
- Change the collision limit from
28 to 12, then 60. Which feels fair? Explain why the visible sizes matter.
- Add a
value property of 1, 2, or 3 to every apple. Display the value and add a.value to the score.
- Add one rotten apple with
kind: 'rotten'. It should subtract 2 points instead of adding.
- When
apples.length == 0, show “Paddock cleared!” in the centre. This is a new 'won' state hiding inside an array fact.
- Debugging test: change the loop to count forward. Put two apples close together and observe the skipped-item bug. Then restore the backward loop.
Next session → c14: Build a Mini-game
You now have the two missing game ingredients: state and collisions. Next you will combine them with arrays, randomness, functions, and debugging into one complete game.