xxxxxxxxxx
133
let fireworks = [];
let gravity;
function setup() {
color(random(0,255),random(0,255),random(0,255));
createCanvas(400, 400);
gravity = createVector(0, 0.2);
let button = createButton('Launch Fireworks');
button.mousePressed(launchFirework);
}
function draw() {
color(random(0,255),random(0,255),random(0,255));
//background(random(0,255),random(0,255),random(0,255));
for (let i = fireworks.length - 1; i >= 0; i--) {
color(random(0,255),random(0,255),random(0,255));
fireworks[i].update();
fireworks[i].show();
if (fireworks[i].done()) {
fireworks.splice(i, 1);
}
}
}
function launchFirework() {
let firework = new Firework();
fireworks.push(firework);
}
class Firework {
constructor() {
color(random(0,255),random(0,255),random(0,255));
this.firework = new Particle(random(width), height, true);
this.exploded = false;
this.particles = [];
}
done() {
return this.exploded && this.particles.length === 0;
}
update() {
if (!this.exploded) {
this.firework.applyForce(gravity);
this.firework.update();
if (this.firework.velocity.y >= 0) {
this.exploded = true;
this.explode();
}
}
for (let i = this.particles.length - 1; i >= 0; i--) {
this.particles[i].applyForce(gravity);
this.particles[i].update();
if (this.particles[i].done()) {
this.particles.splice(i, 1);
}
}
}
explode() {
for (let i = 0; i < 100; i++) {
let particle = new Particle(this.firework.position.x, this.firework.position.y);
this.particles.push(particle);
}
}
show() {
if (!this.exploded) {
fill(random(0,255),random(0,255),random(0,255));
this.firework.show();
}
for (let i = 0; i < this.particles.length; i++) {
fill(random(0,255),random(0,255),random(0,255));
this.particles[i].show();
}
}
}
class Particle {
constructor(x, y, firework = false) {
this.position = createVector(x, y);
color(random(0,255),random(0,255),random(0,255));
this.firework = firework;
if (this.firework) {
this.velocity = createVector(0, random(-12, -10));
} else {
this.velocity = p5.Vector.random2D();
this.velocity.mult(random(2, 100));
}
this.acceleration = createVector(0, 0);
this.lifespan = 255;
}
applyForce(force) {
fill(random(0,255),random(0,255),random(0,255));
this.acceleration.add(force);
}
update() {
if (!this.firework) {
fill(random(0,255),random(0,255),random(0,255));
this.velocity.mult(0.9);
this.lifespan -= 10;
}
this.velocity.add(this.acceleration);
this.position.add(this.velocity);
this.acceleration.mult(0);
}
done() {
return this.lifespan < 0;
color(random(0,255),random(0,255),random(0,255));
}
show() {
colorMode(RGB);
color(random(0,255),random(0,255),random(0,255));
if (this.firework) {
color(random(0,255),random(0,255),random(0,255));
stroke(255, this.lifespan);
strokeWeight(15);
} else {
color(random(0,255),random(0,255),random(0,255));
stroke(255, this.lifespan);
strokeWeight(5);
}
point(this.position.x, this.position.y);
color(random(0,255),random(0,255),random(0,255));
}
}