preload()
preload() is a special p5.js function that runs before setup() and draw(). It is the ideal place to load fonts, images, and initialize any objects (like p5.sound oscillators) that must exist before the game starts. All six sounds are initialized once here and reused throughout the game by changing their frequency and amplitude.
function preload() {
gameFont = loadFont('https://unpkg.com/@fontsource/press-start-2p@5.0.0/files/press-start-2p-latin-400-normal.woff');
playerShootSound = new p5.Oscillator('sine');
playerShootSound.freq(600);
playerShootSound.amp(0, 0.1);
playerShootSound.start();
alienShootSound = new p5.Oscillator('triangle');
alienShootSound.freq(200);
alienShootSound.amp(0, 0.1);
alienShootSound.start();
alienHitSound = new p5.Oscillator('square');
alienHitSound.freq(800);
alienHitSound.amp(0, 0.1);
alienHitSound.start();
playerHitSound = new p5.Oscillator('sawtooth');
playerHitSound.freq(100);
playerHitSound.amp(0, 0.1);
playerHitSound.start();
gameOverSound = new p5.Oscillator('sine');
gameOverSound.freq(50);
gameOverSound.amp(0, 0.1);
gameOverSound.start();
winSound = new p5.Oscillator('sine');
winSound.freq(1000);
winSound.amp(0, 0.1);
winSound.start();
}
Line-by-line explanation (5 lines)
🔧 Subcomponents:
gameFont = loadFont('https://unpkg.com/@fontsource/press-start-2p@5.0.0/files/press-start-2p-latin-400-normal.woff');
Loads a pixel-art font from CDN to give the game authentic retro arcade text
playerShootSound = new p5.Oscillator('sine'); playerShootSound.freq(600); playerShootSound.amp(0, 0.1); playerShootSound.start();
Creates six procedural sound generators (sine, triangle, square, sawtooth waves) that play sound effects without loading audio files
gameFont = loadFont('https://unpkg.com/@fontsource/press-start-2p@5.0.0/files/press-start-2p-latin-400-normal.woff');- Fetches a retro pixel font from the @fontsource CDN and stores it in the global gameFont variable—this happens before setup() runs
playerShootSound = new p5.Oscillator('sine');- Creates a sine-wave oscillator object; this will generate the tone when the player shoots
playerShootSound.freq(600);- Sets the frequency to 600 Hz (hertz), which corresponds to a particular musical pitch—higher numbers sound higher
playerShootSound.amp(0, 0.1);- Sets the amplitude (volume) to 0 with a 0.1-second fade time, keeping the oscillator silent until it's time to play
playerShootSound.start();- Starts the oscillator running continuously in the background at zero volume; we will animate the volume up when a shot fires