xxxxxxxxxx
56
let particles = [];
let backgroundColor;
function setup() {
createCanvas(800, 600);
backgroundColor = color(220);
}
function draw() {
background(backgroundColor);
for (let particle of particles) {
particle.update();
particle.display();
}
}
function keyPressed() {
if (key === ' ') {
// Change the background color randomly when spacebar is pressed
backgroundColor = color(random(255), random(255), random(255));
}
}
function mousePressed() {
// Add a new particle at the mouse position when the mouse is clicked
let newParticle = new Particle(mouseX, mouseY);
particles.push(newParticle);
}
class Particle {
constructor(x, y) {
this.position = createVector(x, y);
this.velocity = p5.Vector.random2D().mult(random(2, 5));
this.radius = random(5, 20);
this.color = color(random(255), random(255), random(255), 150);
}
update() {
this.position.add(this.velocity);
// Bounce off edges
if (this.position.x < 0 || this.position.x > width) {
this.velocity.x *= -1;
}
if (this.position.y < 0 || this.position.y > height) {
this.velocity.y *= -1;
}
}
display() {
noStroke();
fill(this.color);
ellipse(this.position.x, this.position.y, this.radius * 2);
}
}