preload()
preload() runs once before setup() and is the ideal place to load assets like images, sounds, and fonts. By creating oscillators here, we avoid delays during gameplay. p5.Oscillator generates sounds from math, while PolySynth can play chords—both are great for simple sound effects without external files.
function preload() {
// Placeholder sounds using p5.sound oscillators
// These will create audible sounds without needing external files.
// For actual sound effects, you would use:
// shootSound = loadSound('assets/shoot.wav');
// hitSound = loadSound('assets/hit.wav');
// winSound = loadSound('assets/win.wav');
// loseSound = loadSound('assets/lose.wav');
// Shoot sound: short, high-pitched sine wave
shootSound = new p5.Oscillator('sine');
shootSound.freq(800);
shootSound.amp(0); // Start silent
shootSound.stop(); // Ensure it's stopped initially
// Hit sound: short, slightly lower-pitched triangle wave
hitSound = new p5.Oscillator('triangle');
hitSound.freq(400);
hitSound.amp(0); // Start silent
hitSound.stop();
// Win sound: short, rising arpeggio (PolySynth for multiple notes)
winSound = new p5.PolySynth();
// FIX: Use setAmp() for p5.PolySynth objects
winSound.setAmp(0); // Start silent
winSound.stop();
// Lose sound: short, falling arpeggio (PolySynth for multiple notes)
loseSound = new p5.PolySynth();
// FIX: Use setAmp() for p5.PolySynth objects
loseSound.setAmp(0); // Start silent
loseSound.stop();
}
Line-by-line explanation (7 lines)
🔧 Subcomponents:
shootSound = new p5.Oscillator('sine');
Creates a sine-wave oscillator for the shoot sound effect without loading external audio files
winSound = new p5.PolySynth();
Creates a PolySynth object capable of playing multiple notes simultaneously for the win sound arpeggio
shootSound = new p5.Oscillator('sine');- Creates a sine-wave oscillator object that will generate the shooting sound—sine waves have a smooth, pure tone
shootSound.freq(800);- Sets the frequency of the oscillator to 800 Hz, a high pitch suitable for a 'pew' sound
shootSound.amp(0);- Sets the amplitude (volume) to 0 so the sound is silent until we explicitly start it during gameplay
hitSound = new p5.Oscillator('triangle');- Creates a triangle-wave oscillator for the hit sound—triangle waves sound slightly buzzy compared to sine waves
hitSound.freq(400);- Sets the hit sound frequency to 400 Hz, lower than the shoot sound to differentiate the audio feedback
winSound = new p5.PolySynth();- Creates a PolySynth object that can play multiple notes with different pitches and timing, used for victory music
loseSound = new p5.PolySynth();- Creates another PolySynth for the lose sound, which will play falling notes to signal defeat