setup()
setup() runs once when the sketch first loads. This is where you initialize the canvas size, create objects that last the whole game, and prepare audio and text settings. Everything you set up here will be available in the draw() loop.
function setup() {
createCanvas(windowWidth, windowHeight);
player = new Player();
ground = new Ground(0, height - 50, width, 50); // Ground at the bottom
// --- p5.sound initialization ---
// userStartAudio() is essential for audio to play, especially in browsers
// that block autoplay. It's usually called on a user gesture.
userStartAudio(); // https://p5js.org/reference/p5/userStartAudio/
beatOsc = new p5.Oscillator('sine'); // Create a sine wave oscillator
beatOsc.freq(440); // Set frequency to A4 (440 Hz)
beatOsc.amp(0); // Start silent
beatOsc.start(); // Start the oscillator (but it's silent)
// --- End p5.sound initialization ---
textAlign(CENTER, CENTER);
textSize(32);
fill(255); // White text
}
Line-by-line explanation (9 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight);
Sets up a canvas that fills your entire window and creates the Player and Ground objects
beatOsc = new p5.Oscillator('sine');
Creates a sine wave sound generator that will produce the rhythmic beat during gameplay
createCanvas(windowWidth, windowHeight);- Creates a canvas that covers your entire window—the game will resize if you stretch your browser
player = new Player();- Creates a new Player object with starting position, size, and physics properties
ground = new Ground(0, height - 50, width, 50);- Creates a green ground rectangle at the bottom of the canvas, 50 pixels tall
userStartAudio();- Tells the browser that audio is about to play—many browsers require a user action before allowing sound
beatOsc = new p5.Oscillator('sine');- Creates a sine wave oscillator (a pure electronic tone generator) for the background beat
beatOsc.freq(440);- Sets the oscillator's frequency to 440 Hz, which is the musical note A4 (a pleasant middle pitch)
beatOsc.amp(0);- Sets the oscillator's volume to 0 so it starts silent—we'll turn it on during gameplay
beatOsc.start();- Starts the oscillator running in the background, but inaudibly because its amplitude is 0
textAlign(CENTER, CENTER);- Centers all text both horizontally and vertically around the coordinates you provide