setup()
setup() runs once when the sketch starts. It initializes the canvas, populates the world with static objects (trees) and dynamic ones (birds), sets up audio, and builds the UI. The WEBGL mode is critical—without it, 3D rendering with camera transforms and lighting won't work.
function setup() {
cnv = createCanvas(windowWidth, windowHeight, WEBGL);
document.getElementById('start-btn').addEventListener('click', async () => {
cnv.elt.requestPointerLock();
await userStartAudio(); // Start audio context on user gesture
if (musicLoop && !musicLoop.isPlaying) {
musicLoop.start(); // Start the background music
}
});
// Generate realistic, massive forest
for (let i = 0; i < 200; i++) {
trees.push({
x: random(-4000, 4000),
z: random(-4000, 4000),
size: random(1.5, 4.0)
});
}
for (let i = 0; i < 15; i++) ducks.push(new Target());
setupAudio();
buildShopUI();
}
Line-by-line explanation (9 lines)
🔧 Subcomponents:
cnv.elt.requestPointerLock();
Hides the cursor and traps mouse input within the canvas for immersive first-person control
for (let i = 0; i < 200; i++) {
trees.push({
x: random(-4000, 4000),
z: random(-4000, 4000),
size: random(1.5, 4.0)
});
}
Randomly scatters 200 trees across a wide 4000×4000 unit area with varied sizes for depth perception
for (let i = 0; i < 15; i++) ducks.push(new Target());
Creates 15 bird targets ready to fly and be shot at
cnv = createCanvas(windowWidth, windowHeight, WEBGL);- Creates a full-screen WEBGL canvas—the third argument WEBGL enables 3D rendering with lighting, transforms, and depth
document.getElementById('start-btn').addEventListener('click', async () => {- Waits for the player to click START before locking the mouse and starting audio—browsers require user interaction to begin audio
cnv.elt.requestPointerLock();- Locks the mouse cursor to the canvas and hides it, so your view can be controlled by raw mouse movement
await userStartAudio();- Initializes the p5.sound context—browsers block audio until a user gesture like a click happens
if (musicLoop && !musicLoop.isPlaying) { musicLoop.start();- Checks if the background music loop exists and isn't already playing, then starts it
for (let i = 0; i < 200; i++) { trees.push({ x: random(-4000, 4000), z: random(-4000, 4000), size: random(1.5, 4.0) }); }- Loops 200 times, pushing a tree object with random position (x and z in a 4000-unit square) and random size (1.5 to 4 times normal) into the trees array
for (let i = 0; i < 15; i++) ducks.push(new Target());- Loops 15 times, creating a new Target instance (a bird) and adding it to the ducks array—these birds will spawn around the player
setupAudio();- Calls the audio initialization function to set up oscillators, envelopes, and the background music loop
buildShopUI();- Populates the HTML shop menu with all weapon and bird options dynamically