xxxxxxxxxx
92
// goal : https://i.imgur.com/8NCp7x4.mp4
const maxLength = 5000; // Maximum length of the balls array
let balls = [];
let soundQueue = []; // Queue to manage playing oscillators
let maxSounds = 3; // Maximum number of simultaneous sounds
let G;
function setup() {
createCanvas(400, 400);
spawnBall();
// G = createVector(0, 1);
polySynth = new p5.PolySynth();
}
function spawnBall() {
balls.push(
{p: createVector(random()*width, random(0, height*.5)),
a: createVector(0,.2),
v: createVector()
})
}
function tickBalls() {
// Apply gravity, check for floor collision, bounce, and spawn new ball if needed
for (let i = balls.length - 1; i >= 0; i--) { // Iterate backwards to safely modify the array
const b = balls[i];
b.v.add(b.a); // Apply acceleration to velocity
b.p.add(b.v); // Apply velocity to position
// Check for collision with the floor
if (b.p.y >= height) {
b.p.y = height; // Correct position to be on the floor
b.v.y *= -1; // Reverse and reduce velocity for bounce
b.v.x *= 0.99; // Apply some friction to horizontal movement
spawnBall();
playOscillatorSound();
}
}
// Check if the balls array exceeds the maximum allowed length
if (balls.length > maxLength) {
const removeCount = balls.length - maxLength; // Number of balls to remove
balls.splice(0, removeCount); // Remove the first N balls
}
}
function playOscillatorSound() {
// Check if we can play a new sound
if (soundQueue.length < maxSounds) {
let osc = new p5.Oscillator('sine');
osc.freq(random(100, 1200)); // Set a random frequency for variety
osc.start();
osc.amp(0.5, 0.05); // Set amplitude with a quick fade in
osc.amp(0, 0.5, 0.5); // Fade out after 0.5 seconds
// Add the oscillator to the queue
soundQueue.push(osc);
// Schedule removal of the oscillator from the queue
setTimeout(() => {
osc.stop();
soundQueue.shift(); // Remove the oldest sound from the queue
}, 1000); // Remove after 1 second, adjust based on the desired sound duration
}
}
function drawBalls() {
// Draw each ball
const l = balls.length
for (const [i,b] of balls.entries()) {
noStroke();
fill(100, i/l * 255, 240); // A nice ball color
circle(b.p.x, b.p.y, 20); // Draw ball with a radius of 10
}
}
function draw() {
background(220);
tickBalls(); // Update balls' positions
drawBalls(); // Draw balls on the canvas
}