xxxxxxxxxx
63
var synth;
//SuperMario pitches from low to high
var notes = ["C4", "E4", "G4", "A4", "A#4", "B4", "C5", "E5"];
var keys = ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k'];
var amp; //amplitude of waves
var waves = []; //array of waves
function setup() {
createCanvas(800, 800);
synth = new Tone.Synth().toMaster();
// 8 waves at different maoving speed, period, and axis
for (i = 0; i < 8; i++) {
waves[i] = new Wave((i + 1) * 0.05, (9 - i) * 40, 100 + i * height / 10);
}
}
function draw() {
background(0);
for (i = 0; i < 8; i++) {
//if key[i] is pressed, play note[i] and activate waves[i] with amp
if (keyIsPressed & key === keys[i]) {
synth.triggerAttackRelease(notes[i], 0.1);
amp = 20;
} else {
amp = 0;
}
waves[i].renderWave(amp);
}
}
//Wave constructor
function Wave(tempTheta, tempPeriod, tempAxis) {
this.xspacing = 3;
this.x = 0.02;
this.w = width + 16;
this.theta = tempTheta; //moving speed of waves
this.period = tempPeriod;
this.axis = tempAxis; //y value of wave axis
this.dx = (TWO_PI / this.period) * this.xspacing;
this.y = new Array(floor(this.w / this.xspacing));
this.renderWave = function(amp) {
this.theta += tempTheta;
this.x = this.theta;
// console.log(this.x);
for (var i = 0; i < this.y.length; i++) {
this.y[i] = sin(this.x) * amp;
this.x += this.dx;
}
noStroke();
fill(255);
for (var j = 0; j < this.y.length; j++) {
ellipse(j * this.xspacing, tempAxis + this.y[j], 5, 5);
}
}
//reference: https://p5js.org/examples/math-sine-wave.html
}