Bubble (class)
This class packages all the data and behavior for a single bubble into one reusable blueprint. Every bubble on screen is a separate instance, letting you manage dozens of independent objects with the same code.
🔬 This uses the bubble's radius as the click tolerance. What happens if you multiply this.r by 1.5 to make bubbles easier to pop, or by 0.5 to make popping require pixel-perfect accuracy?
isClicked(mx, my) { return dist(mx, my, this.x, this.y) < this.r; }
class Bubble {
constructor(x, y, r, c, s) {
this.x = x; this.y = y; this.r = r; this.color = c; this.speed = s;
}
move() { this.y -= this.speed; }
display() {
fill(this.color); circle(this.x, this.y, this.r * 2);
fill(255, 100); circle(this.x - this.r / 3, this.y - this.r / 3, this.r * 0.7);
}
isOffScreen() { return this.y < -this.r; }
isClicked(mx, my) { return dist(mx, my, this.x, this.y) < this.r; }
}
Line-by-line explanation (7 lines)
🔧 Subcomponents:
constructor(x, y, r, c, s) { this.x = x; this.y = y; this.r = r; this.color = c; this.speed = s; }
Stores the bubble's starting position, radius, color, and speed as properties on the object
fill(255, 100); circle(this.x - this.r / 3, this.y - this.r / 3, this.r * 0.7);
Draws a smaller semi-transparent white circle offset toward the top-left to fake a glossy 3D highlight
return dist(mx, my, this.x, this.y) < this.r;
Uses distance math to check if the mouse click point falls within the bubble's circular area
constructor(x, y, r, c, s) {- Runs once when a new Bubble is created, receiving its starting x/y position, radius, color, and speed
this.x = x; this.y = y; this.r = r; this.color = c; this.speed = s;- Saves each parameter onto the object so it can be reused later in move() and display()
move() { this.y -= this.speed; }- Decreases the y position each frame - since y grows downward in p5.js, subtracting makes the bubble rise
fill(this.color); circle(this.x, this.y, this.r * 2);- Sets the fill color to the bubble's assigned color and draws the main circle body (diameter is twice the radius)
fill(255, 100); circle(this.x - this.r / 3, this.y - this.r / 3, this.r * 0.7);- Draws a small semi-transparent white circle shifted up and left to simulate a glossy light reflection
isOffScreen() { return this.y < -this.r; }- Returns true once the bubble has fully floated above the top edge of the canvas, so it can be removed
isClicked(mx, my) { return dist(mx, my, this.x, this.y) < this.r; }- Calculates the straight-line distance between the mouse click and the bubble's center; if it's less than the radius, the click is inside the circle