🔬 This collision detection checks three conditions: the ball's bottom has reached the player's top, AND the ball is horizontally within the box. What happens if you remove one of these conditions (like delete the item.x > player.x line) and see if balls get caught without proper overlap?
// Check collision with player
if (item.y + item.size/2 > player.y &&
item.x > player.x &&
item.x < player.x + player.w) {
score += 10;
items.splice(i, 1);
}
🔬 The loop counts backward (i--) instead of forward. What would happen if you changed it to i++ (forward counting) and then try to remove items during the loop? Try it and notice if the game behaves strangely.
for (let i = items.length - 1; i >= 0; i--) {
let item = items[i];
item.y += item.speed;
function draw() {
background(30, 30, 40);
// Spawn items
if (frameCount % 60 === 0) {
items.push({
x: random(20, width - 20),
y: 0,
size: random(15, 30),
speed: random(2, 5),
color: color(random(255), random(255), random(255))
});
}
// Update & draw items
for (let i = items.length - 1; i >= 0; i--) {
let item = items[i];
item.y += item.speed;
fill(item.color);
noStroke();
ellipse(item.x, item.y, item.size);
// Check collision with player
if (item.y + item.size/2 > player.y &&
item.x > player.x &&
item.x < player.x + player.w) {
score += 10;
items.splice(i, 1);
}
// Remove if off screen
if (item.y > height) {
items.splice(i, 1);
}
}
// Draw player
player.x = mouseX - player.w / 2;
player.x = constrain(player.x, 0, width - player.w);
fill(100, 200, 255);
rect(player.x, player.y, player.w, player.h, 5);
// Score
fill(255);
textSize(24);
textAlign(LEFT, TOP);
text('Score: ' + score, 20, 20);
}