xxxxxxxxxx
101
let fireworks = [];
function setup() {
createCanvas(500, 500);
}
class Firework {
constructor(startX, finalY) {
this.startX = startX; //launch position x
this.startY = height; //launch position y
this.finalY = finalY; //y position to explode
this.speed = random(4, 10); //speed to travel up
this.exploded = false; //explosion status (to activate it later)
this.explosionSize = random(10, 70); //size of explosion
this.explosionAlpha = 255; //variable to let explosion fade
}
moveUp() {
//moving the firework up
this.startY -= this.speed; //negative because y start is height
}
show() {
//fireworks 'rocket' appearance
stroke(102, 84, 46);
rect(this.startX - 2, this.startY - 10, 4, 20);
}
reachFinalY() {
//had to add this for being able to detect final posY.
return this.startY <= this.finalY;
}
explode() {
//change status of explosion to true
this.exploded = true;
}
showExplosion() {
//visual features of the explosion
// random colored rays expanding outward from center
stroke(random(20, 120) + 100, random(20, 120) + 100, random(20, 120) + 100);
angleMode(DEGREES);
for (let i = 0; i <= 12; i++) {
const angle = 30 * i; //30 * 12 = 360 so 12 lines around the circle
const endX = this.startX + cos(angle) * this.explosionSize/1.5; //vary size
const endY = this.finalY + sin(angle) * this.explosionSize/1.5;
line(this.startX, this.finalY, endX, endY);
}
// circle that fades
noStroke();
fill(
random(20, 120) + 80,
random(20, 120) + 80,
random(20, 120) + 80,
this.explosionAlpha);
circle(this.startX, this.finalY, this.explosionSize);
this.explosionSize += random(2, 5); //increase the explosion size
this.explosionAlpha -= 3; //decrease the alpha
}
faded() { //return next opacity to full
return this.explosionAlpha <= 0;
}
}
// create new object upon every mouse clicked
function mouseClicked() {
let newFirework = new Firework(mouseX, mouseY); //creates new object with cursors x and y parameters for the objects startX and startY variables.
fireworks.push(newFirework); //add new firework object into array
}
function draw() {
background(40,40,100);
push();
fill(177,177,224);
stroke(202,179,0);
textAlign(CENTER);
textSize(50);
text('click for fireworks!', 250, 100)
pop();
//for loop to add firework to array
for (let i = fireworks.length - 1; i >= 0; i--) {
firework = fireworks[i];
firework.moveUp();
if (firework.exploded) {
firework.showExplosion();
if (firework.faded()) {
fireworks.splice(i, 1); //remove rocket after exploded
}
} else {
firework.show();
if (firework.reachFinalY()) {
firework.explode();
}
}
}
}