preload()
preload() runs once before setup() and is the perfect place to load sounds, images, or other assets. Notice how all oscillators start with amp(0) so they are silent until we explicitly make them audible in reproducirSonido(). This pattern prevents unexpected noise when the sketch loads.
function preload() {
// Precargamos los sonidos
// Usamos p5.Oscillator para sonidos simples, podrías cargar archivos .mp3 o .wav si los tuvieras.
sonidoAtrapar = new p5.Oscillator();
sonidoAtrapar.setType('triangle');
sonidoAtrapar.freq(500);
sonidoAtrapar.amp(0); // Empieza en silencio
sonidoAtrapar.start();
sonidoPerder = new p5.Oscillator();
sonidoPerder.setType('sawtooth');
sonidoPerder.freq(100);
sonidoPerder.amp(0);
sonidoPerder.start();
sonidoGameOver = new p5.Oscillator();
sonidoGameOver.setType('sine');
sonidoGameOver.freq(50);
sonidoGameOver.amp(0);
sonidoGameOver.start();
// Música de fondo simple
musicaFondo = new p5.Oscillator();
musicaFondo.setType('sine');
musicaFondo.freq(220); // Nota La 2
musicaFondo.amp(0.1); // Volumen bajo
musicaFondo.start();
}
Line-by-line explanation (7 lines)
🔧 Subcomponents:
sonidoAtrapar = new p5.Oscillator();
Creates a triangle-wave oscillator that plays when you catch a fruit
sonidoPerder = new p5.Oscillator();
Creates a sawtooth-wave oscillator that plays when a fruit falls unmissed
sonidoGameOver = new p5.Oscillator();
Creates a sine-wave oscillator that plays when the game ends
musicaFondo = new p5.Oscillator();
Creates a sine-wave oscillator that loops quietly during gameplay
sonidoAtrapar = new p5.Oscillator();- Creates a new oscillator object and assigns it to the global variable sonidoAtrapar
sonidoAtrapar.setType('triangle');- Sets the oscillator to produce a triangle wave, which sounds smooth and musical
sonidoAtrapar.freq(500);- Sets the frequency (pitch) to 500 Hz—a mid-range note that sounds satisfying when you catch a fruit
sonidoAtrapar.amp(0);- Sets the amplitude (volume) to 0, so the sound starts silent and only plays when triggered later
sonidoAtrapar.start();- Starts the oscillator running—it stays on the entire game but silent until we change its amplitude
musicaFondo.freq(220); // Nota La 2- Sets background music to 220 Hz (the note A3), a pleasant low frequency that loops continuously
musicaFondo.amp(0.1); // Volumen bajo- Sets background music to 10% volume so it does not drown out catch/miss sounds