xxxxxxxxxx
100
let fireworks = [];
function setup() {
createCanvas(600, 600);
stroke(255);
strokeWeight(2);
background(255);
}
function draw() {
// Display and update fireworks
for (let i = fireworks.length - 1; i >= 0; i--) {
fireworks[i].update();
fireworks[i].display();
if (fireworks[i].isFinished()) {
fireworks.splice(i, 1); // Remove finished fireworks
}
}
}
function mouseClicked() {
// Launch a new firework at the mouse position
let firework = new Firework(mouseX, height);
fireworks.push(firework);
}
class Firework {
constructor(x, y) {
this.pos = createVector(x, y);
this.vel = createVector(random(-2, 2), random(-10, -5));
this.acc = createVector(0, 0.2);
this.explosion = false;
this.particles = [];
this.color = color(random(255), random(255), random(255));
}
update() {
if (!this.explosion) {
this.vel.add(this.acc);
this.pos.add(this.vel);
if (this.vel.y >= 0) {
this.explosion = true;
this.explode();
}
}
// Update and display particles
for (let i = this.particles.length - 1; i >= 0; i--) {
this.particles[i].update();
this.particles[i].display();
if (this.particles[i].isFinished()) {
this.particles.splice(i, 1); // Remove finished particles
}
}
}
explode() {
for (let i = 0; i < 100; i++) {
let particle = new Particle(this.pos.x, this.pos.y, this.color);
this.particles.push(particle);
}
}
isFinished() {
return this.explosion && this.particles.length === 0;
}
display() {
if (!this.explosion) {
point(this.pos.x, this.pos.y);
}
}
}
class Particle {
constructor(x, y, color) {
this.pos = createVector(x, y);
this.vel = p5.Vector.random2D().mult(random(2, 10));
this.acc = createVector(0, 0.2);
this.color = color;
this.lifespan = 255;
}
update() {
this.vel.add(this.acc);
this.pos.add(this.vel);
this.lifespan -= 5;
}
isFinished() {
return this.lifespan <= 0;
}
display() {
noStroke();
fill(this.color, this.lifespan);
ellipse(this.pos.x, this.pos.y, 10);
}
}