Beam constructor()
The constructor runs once for each Beam object when setup() creates it, setting up all the state (position index, color, sound) that the beam will need for its entire lifetime.
constructor(index, total, freq) {
this.index = index;
this.total = total;
this.freq = freq;
// Hue from 0..360 across beams for rainbow
this.hue = map(index, 0, total - 1, 0, 360);
this.isActive = false; // mouse currently inside this beam
this.lastTriggerTime = -1000; // for glow flash
this.started = false; // has osc.start() been called yet?
// Create oscillator (from p5.sound)
// https://p5js.org/reference/#/p5.Oscillator
this.osc = new p5.Oscillator('triangle'); // nice, slightly harp-like
this.osc.freq(this.freq);
this.osc.amp(0); // start silent
// We will actually start() after user enables audio
}
Line-by-line explanation (8 lines)
this.index = index; this.total = total; this.freq = freq;- Stores which beam number this is, how many beams exist total, and which musical frequency it should play.
this.hue = map(index, 0, total - 1, 0, 360);- Spreads each beam's color evenly around the 360-degree hue wheel based on its position in the lineup, creating the rainbow effect.
this.isActive = false;- Tracks whether the mouse is currently inside this beam, used to decide when to trigger or release the note.
this.lastTriggerTime = -1000;- Remembers when the beam was last triggered so display() can calculate a fading flash effect; starts far in the past so no flash shows initially.
this.started = false;- Tracks whether the oscillator's start() has been called yet, since browsers require a user gesture before audio can play.
this.osc = new p5.Oscillator('triangle');- Creates a triangle-wave oscillator, which produces a mellow, harp-like tone.
this.osc.freq(this.freq);- Tunes the oscillator to this beam's assigned musical note frequency.
this.osc.amp(0);- Sets the oscillator's volume to zero so it starts silent even after it begins running.