xxxxxxxxxx
79
/************************************************************************
This sketch = https://editor.p5js.org/Anne-Laure/sketches/PjkgJCxSL
Source 3.7: Additive Waves - The Nature of Code after 8'17''
https://www.youtube.com/watch?v=okfZRl4Xw-c
we want a class of waves, adding themselves
Previous sketch : https://editor.p5js.org/Anne-Laure/sketches/JvsbgQAtr
Next sketch :
************************************************************************/
let waves = [] ;
function setup() {
createCanvas(600, 400);
for ( let i = 0 ; i < 5 ; i++ ) {
waves[i] = new Wave( random(20,80), random(100,600), random(TWO_PI) ) ;
}
}
function draw() {
background(0);
noStroke();
for( let x = 0 ; x < width; x += 10 ) {
let y = 0 ;
for (let wave of waves ) {
y += wave.evaluate( x ) ;
// display all waves
// ellipse( x, y + height/2 , 10 ) ;
}
// display all waves added together
ellipse( x, y + height/2 , 16 ) ;
}
for (let wave of waves) {
wave.update();
}
}
/*
wave class with three properties amplitud period (frequency) and phase
phase is the place where the wave is 0
if canvas 600x200
wave with amplitude 100 (height), period 600 (length)
on the wave y = sin( phase + TWO_PI * x / period ) * amplitude
*/
class Wave {
constructor( amp, period, phase ) {
this.amplitude = amp ;
this.period = period ;
this.phase = phase ;
}
evaluate( x ) {
return sin( this.phase + (TWO_PI * x) / this.period ) * this.amplitude ;
}
update() {
this.phase += 0.05 ;
}
}