class Collector
The Collector class is the simplest entity in this sketch. It demonstrates how to use a class to bundle position, size, and behavior together. The move() method shows the two-part input pattern: check for touch (mobile), fall back to mouse (desktop). The constrain() call is crucial—without it, the collector would scroll off-screen.
class Collector {
constructor() {
this.width = collectorWidth;
this.height = collectorHeight;
this.x = width / 2;
this.y = height - this.height / 2 - 10;
this.speed = 10;
}
display() {
fill(50, 200, 50);
noStroke();
rect(this.x, this.y, this.width, this.height, 5);
}
move() {
if (touches.length > 0) {
this.x = touches[0].x;
} else {
this.x = mouseX;
}
this.x = constrain(this.x, this.width / 2, width - this.width / 2);
}
}
Line-by-line explanation (7 lines)
🔧 Subcomponents:
constructor() { ... }
Initializes the collector's position (center-bottom of canvas), size, and speed; runs once when the collector is created
display() { ... }
Draws the collector as a green rounded rectangle at its current position
move() { ... }
Updates the collector's x position to follow touch or mouse input, then constrains it within canvas boundaries
this.width = collectorWidth;- Stores the collector's width (100 pixels) in the instance variable so it can be used in display() and collision checks
this.x = width / 2;- Centers the collector horizontally on the canvas by setting x to half the canvas width
this.y = height - this.height / 2 - 10;- Positions the collector near the bottom of the canvas, with 10 pixels of margin from the true bottom edge
if (touches.length > 0) {- Checks if any fingers are touching the screen; true on mobile devices, false on desktop
this.x = touches[0].x;- On mobile, move the collector to follow the first touch point's x coordinate
this.x = mouseX;- On desktop (fallback), move the collector to follow the mouse's x coordinate
this.x = constrain(this.x, this.width / 2, width - this.width / 2);- Clamps the collector's x position so it never moves outside the canvas—this prevents the collector from half-disappearing at the edges