preload()
preload() runs before setup() and is the ideal place to load sounds, images, or other assets. Using p5.Oscillator and p5.PolySynth allows us to create procedural sounds without needing external audio files—perfect for keeping the sketch self-contained. The amp(0) and stop() calls ensure sounds are silent until explicitly triggered during gameplay.
function preload() {
shootSound = new p5.Oscillator('sine');
shootSound.freq(800);
shootSound.amp(0);
shootSound.stop();
hitSound = new p5.Oscillator('triangle');
hitSound.freq(400);
hitSound.amp(0);
hitSound.stop();
winSound = new p5.PolySynth();
winSound.amp(0);
winSound.stop();
loseSound = new p5.PolySynth();
loseSound.amp(0);
loseSound.stop();
}
Line-by-line explanation (8 lines)
🔧 Subcomponents:
shootSound = new p5.Oscillator('sine');
Creates a sine-wave oscillator for the weapon fire sound
hitSound = new p5.Oscillator('triangle');
Creates a triangle-wave oscillator for enemy hit feedback
winSound = new p5.PolySynth();
Creates a multi-note synthesizer for round/game win sounds
shootSound = new p5.Oscillator('sine');- Creates a new oscillator that generates a sine-wave (smooth, pure tone) for the shooting sound
shootSound.freq(800);- Sets the oscillator's frequency to 800 Hz, a fairly high pitch suitable for a weapon fire sound
shootSound.amp(0);- Starts the oscillator completely silent (amplitude 0) so it only makes noise when explicitly triggered
shootSound.stop();- Ensures the oscillator is in stopped state before the sketch begins playing any sounds
hitSound = new p5.Oscillator('triangle');- Creates a triangle-wave oscillator (slightly brighter than sine) for the hit feedback sound
hitSound.freq(400);- Sets the hit sound frequency to 400 Hz, lower than the shoot sound to provide sonic contrast
winSound = new p5.PolySynth();- Creates a PolySynth object that can play multiple notes simultaneously, enabling the three-note win arpeggio
loseSound = new p5.PolySynth();- Creates a PolySynth object for the three-note losing sound, using the same multi-note capability