setup()
setup() runs once when the sketch starts. It configures the canvas size, text appearance, and initializes all three sound oscillators. The p5.sound library is powerful for creating both simple beeps and complex synthesized sounds—oscillators let you generate pure sine, square, triangle, or sawtooth waves and control their frequency and volume dynamically.
function setup() {
createCanvas(windowWidth, windowHeight);
textAlign(CENTER, CENTER);
textSize(32);
// Initialize p5.sound oscillators for simple effects
sliceSound = new p5.Oscillator('sine');
sliceSound.amp(0);
sliceSound.freq(880); // High pitch for slicing
sliceSound.start();
bombSound = new p5.Oscillator('square');
bombSound.amp(0);
bombSound.freq(100); // Low pitch for bomb
bombSound.start();
missedSound = new p5.Oscillator('triangle');
missedSound.amp(0);
missedSound.freq(220); // Low pitch for missed fruit
missedSound.start();
userStartAudio(); // Required to enable audio playback in browsers
}
Line-by-line explanation (8 lines)
đź”§ Subcomponents:
createCanvas(windowWidth, windowHeight);
Creates a full-screen canvas that fills the entire browser window
textAlign(CENTER, CENTER);
textSize(32);
Centers all text at the point given to text() and sets default font size for UI
sliceSound = new p5.Oscillator('sine');
sliceSound.amp(0);
sliceSound.freq(880);
sliceSound.start();
Creates three synthesizer oscillators (sine, square, triangle) that will play sound effects when triggered
createCanvas(windowWidth, windowHeight);- Creates a canvas that fills the entire browser window—windowWidth and windowHeight are p5.js variables that update if the window resizes
textAlign(CENTER, CENTER);- Centers all text both horizontally and vertically at the coordinates you provide to text()
textSize(32);- Sets the default font size to 32 pixels for all text drawn after this line
sliceSound = new p5.Oscillator('sine');- Creates a sine wave oscillator object that will generate the high-pitched slicing sound
sliceSound.amp(0);- Sets the volume to 0 (silent) initially—it will be ramped up when a fruit is sliced
sliceSound.freq(880);- Sets the frequency to 880 Hz, which is a high musical note (A5) that sounds like a sharp 'slice'
sliceSound.start();- Starts the oscillator running—it stays running in the background until the sketch closes, and we control its volume to trigger sounds
userStartAudio();- Required by modern browsers to allow audio playback—browsers block audio until the user interacts with the page