setup()
setup() runs once at the start and prepares all your variables and canvas settings. WEBGL is p5.js's 3D mode and unlocks translate(), rotate, and z-coordinates. HSB color mode is perfect for rainbow effects because changing hue alone doesn't change brightness.
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
colorMode(HSB, 360, 100, 100, 1);
// Create an overlay instruction text
inst = createDiv('CLICK / TAP & HOLD TO DIVE FASTER');
inst.style('position', 'absolute');
inst.style('bottom', '30px');
inst.style('width', '100%');
inst.style('text-align', 'center');
inst.style('color', 'rgba(255, 255, 255, 0.7)');
inst.style('font-family', 'sans-serif');
inst.style('font-size', '14px');
inst.style('letter-spacing', '3px');
inst.style('pointer-events', 'none');
// Initialize the rings
for (let i = 0; i < numRings; i++) {
rings.push({
z: map(i, 0, numRings, 0, -totalDepth),
hue: map(i, 0, numRings, 0, 360),
active: true // Tracks if the ring is still rendering
});
}
}
Line-by-line explanation (6 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight, WEBGL);
colorMode(HSB, 360, 100, 100, 1);
Enables true 3D drawing with WEBGL and switches to HSB color space for smooth hue cycling
inst = createDiv('CLICK / TAP & HOLD TO DIVE FASTER');
inst.style('position', 'absolute');
inst.style('bottom', '30px');
Creates a DOM element overlay at the bottom of the screen to guide player interaction
for (let i = 0; i < numRings; i++) {
rings.push({
z: map(i, 0, numRings, 0, -totalDepth),
hue: map(i, 0, numRings, 0, 360),
active: true
});
}
Distributes rings evenly from front to back of the tunnel with hues cycling from 0 to 360 degrees
createCanvas(windowWidth, windowHeight, WEBGL)- Creates a full-window 3D canvas using WEBGL renderer, which allows translate(), rotateX(), rotateY() and 3D transformations
colorMode(HSB, 360, 100, 100, 1)- Switches from RGB to HSB (Hue, Saturation, Brightness)—hue ranges 0-360, saturation 0-100, brightness 0-100, alpha 0-1. This makes color cycling easier
inst = createDiv('CLICK / TAP & HOLD TO DIVE FASTER')- Creates a p5.js DOM element containing text and stores it in the inst variable so we can hide it later
inst.style('position', 'absolute')- Positions the text absolutely over the canvas instead of in document flow
z: map(i, 0, numRings, 0, -totalDepth)- Maps ring index i from 0 to numRings onto depth range 0 to -totalDepth, spreading rings evenly in 3D space
hue: map(i, 0, numRings, 0, 360)- Maps ring index onto hue values 0 to 360, giving each ring a different starting color