xxxxxxxxxx
90
let fireworks = [];
function setup() {
createCanvas(800, 600);
}
function draw() {
background(0);
// Update and display each firework
for (let i = fireworks.length - 1; i >= 0; i--) {
fireworks[i].update();
fireworks[i].show();
if (fireworks[i].done()) {
fireworks.splice(i, 1);
}
}
}
function mouseClicked() {
// Create a new firework at mouse position when mouse is clicked
let firework = new Firework(mouseX, mouseY);
fireworks.push(firework);
}
class Firework {
constructor(x, y) {
this.x = x;
this.y = y;
this.particles = [];
this.hue = random(360);
// Create particles for explosion
for (let i = 0; i < 100; i++) {
this.particles.push(new Particle(this.x, this.y, this.hue));
}
}
update() {
// Update particles
for (let particle of this.particles) {
particle.update();
}
}
show() {
// Display particles
for (let particle of this.particles) {
particle.show();
}
}
done() {
// Check if all particles are off the screen
for (let particle of this.particles) {
if (!particle.isOffScreen()) {
return false;
}
}
return true;
}
}
class Particle {
constructor(x, y, hue) {
this.pos = createVector(x, y);
this.vel = p5.Vector.random2D().mult(random(1, 5));
this.acc = createVector(0, 0.1);
this.lifespan = 255;
this.hue = hue;
}
update() {
this.vel.add(this.acc);
this.pos.add(this.vel);
this.lifespan -= 2;
}
show() {
colorMode(HSB);
stroke(this.hue, 255, 255, this.lifespan);
strokeWeight(4);
point(this.pos.x, this.pos.y);
}
isOffScreen() {
return (this.pos.x < 0 || this.pos.x > width || this.pos.y < 0 || this.pos.y > height);
}
}