xxxxxxxxxx
let balls = []; // array to store the ball objects
let notes = [261.63, 293.66, 329.63, 349.23, 392, 440, 493.88, 523.25]; // frequencies of the 8 notes
var palette = ["#fab515", "#d7312e", "#2a71af", "#ad7347", "#ad7347", "#1d1d1b"];
let envelope, oscillator;
let interval = 100; // interval at which to play each note, in milliseconds
function setup() {
size = min(windowWidth, windowHeight);
createCanvas(size, size);
noStroke();
// tone
envelope = new p5.Env();
envelope.setADSR(0.01, 0.1, 0.1, 0.1);
oscillator = new p5.Oscillator();
oscillator.amp(envelope);
oscillator.start();
interval = random(100,600);
// create 5 ball objects and add them to the array
for (let i = 0; i < 10; i++) {
chosenCol = int(random(0, palette.length));
let ball = {
x: random(width), // random initial x position
y: random(height), // random initial y position
vx: random(-5, 5), // random x velocity
vy: random(-5, 5), // random y velocity
size: random(size/10, size/5), // random size
color: color(palette[chosenCol]) // random color
};
balls.push(ball);
}
}
function draw() {
background("#f9f0de");
// update and draw each ball
for (let i = 0; i < balls.length; i++) {
let ball = balls[i];
// update ball position
ball.x += ball.vx;
ball.y += ball.vy;
// bounce the ball off the walls
if (ball.x > width || ball.x < 0) {
playNote();
chosenCol = int(random(0, palette.length));
ball.color = palette[chosenCol];
ball.vx *= -1;
}
if (ball.y > height || ball.y < 0) {
playNote();
chosenCol = int(random(0, palette.length));
ball.color = palette[chosenCol];
ball.vy *= -1;
}
// bounce the ball off other balls
for (let j = 0; j < balls.length; j++) {
if (i !== j) { // don't bounce the ball off itself
let other = balls[j];
let d = dist(ball.x, ball.y, other.x, other.y);
if (d < ball.size / 2 + other.size / 2) {
// balls are colliding, so bounce them off each other
ball.vx *= -1;
ball.vy *= -1;
other.vx *= -1;
other.vy *= -1;
}
}
}
// draw the ball
fill(ball.color);
ellipse(ball.x, ball.y, ball.size, ball.size);
}
}
function playNote() {
let randomIndex = floor(random(notes.length)); // select a random note
oscillator.freq(notes[randomIndex]);
envelope.play();
}