xxxxxxxxxx
104
let osc, delay, env;
let noiseOffset = 0;
let prevHit;
function setup(){
let cnv = createCanvas(windowWidth, windowHeight);
cnv.mouseClicked(togglePlay);
//fft = new p5.FFT(32);
osc = new p5.TriOsc(440);
//osc.connect(fft);
colorMode(HSB, 360, 100, 100);
noStroke();
prevHit = false;
}
function draw(){
env = new p5.Envelope(0.01);
let hueValue = noise(noiseOffset) * 360;
background(hueValue, 60, 60);
let cols = floor(width / 120) + 1;
let rows = floor(height / 120) + 1;
let spacing = 120;
let hitAny = false;
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let x = i * spacing + 60;
let y = j * spacing + 60;
let hueValue = noise(i * 0.1, j * 0.1, noiseOffset) * 360;
let complementaryHue = (hueValue + 180) % 360;
fill(complementaryHue, 60, 60);
//square(x-50, y-50, 100, 30*noise(frameCount/1000 + i*j)+5);
let xoff = 100*noise(j)-50;
if (i%2){
let hit = isMouseInsideTriangle(x-80 + xoff, y-50, x+80 + xoff, y-50, x + xoff, y+50);
if (hit){
hitAny = true;
if (!prevHit){
osc.amp(env);
osc.start();
}
fill(hueValue,60,60);
osc.freq(map(mouseX*mouseY, 0, width*height, 10, 500));
}
triangle(x-80 + xoff, y-50, x+80 + xoff, y-50, x + xoff, y+50)
}
else{
let hit = isMouseInsideTriangle(x-80 + xoff, y+50, x+80 + xoff, y+50, x + xoff, y-50);
if (hit){
hitAny = true;
if (!prevHit){
osc.amp(env);
osc.start();
}
fill(hueValue,60,60);
osc.freq(map(mouseX*mouseY, 0, width*height, 10, 500));
}
triangle(x-80 + xoff, y+50, x+80 + xoff, y+50, x + xoff, y-50)
}
}
}
if (!hitAny){
prevHit = false;
setTimeout(() => {
osc.stop();
}, 200);
}else{
prevHit = true;
}
noiseOffset += 0.003;
fill(100);
//stroke(100);
//textSize(50);
//describe('The sketch displays the frequency spectrum and waveform of the sound that plays.');
}
function togglePlay() {
osc.start();
}
function isMouseInsideTriangle(x1, y1, x2, y2, x3, y3) {
function sign(px, py, ax, ay, bx, by) {
return (px - bx) * (ay - by) - (ax - bx) * (py - by);
}
let d1 = sign(mouseX, mouseY, x1, y1, x2, y2);
let d2 = sign(mouseX, mouseY, x2, y2, x3, y3);
let d3 = sign(mouseX, mouseY, x3, y3, x1, y1);
return (d1 >= 0 && d2 >= 0 && d3 >= 0) || (d1 <= 0 && d2 <= 0 && d3 <= 0);
}