xxxxxxxxxx
100
let fireworks = [];
function setup() {
createCanvas(400, 400);
}
function draw() {
background(0,0,0,60);
for (let i = fireworks.length - 1; i >= 0; i--) {
//iterate in reverse order
updateFirework(fireworks[i]);
showFirework(fireworks[i]);
if (fireworks[i].done) {
fireworks.splice(i, 1);
} //deletes the firework if exploded
}
}
function mousePressed() {
let newFirework = createFirework(mouseX, mouseY); //creates new firework at location of mouse click
fireworks.push(newFirework); //adds it to array
}
function createFirework(x, y) {
return {
x: x,
y: height, //firework starts from bottom
targetY: y, //target vertical position where the firework should explode
radius: 2, //radius of the dot representing the firework before it explodes
isExploded: false, //flag
lines: [], //array for lines of firework during explosion
done: false, //flag
};
}
function updateFirework(firework) {
if (!firework.isExploded) {
firework.y -= 15; //upward speed
if (firework.y <= firework.targetY) { //once reaches or crosses spot
explodeFirework(firework); }
}
for (let i = firework.lines.length - 1; i >= 0; i--){
if (firework.isExploded && firework.lines[i].length < firework.lines[i].maxLength) { //until lines of firework reach max
firework.lines[i].length += 10; } //grows firework
}
if (firework.isExploded) {
let reachedMax = true;
for (let i = 0; i < firework.lines.length; i++) {
if (firework.lines[i].length < firework.lines[i].maxLength) { //ensures that each line reached max
reachedMax = false;
break; } //Once a line fails
}
firework.done = reachedMax;
}
else {
firework.done = false; }
}
function explodeFirework(firework) {
firework.isExploded = true;
for (let angle = 0; angle < 360; angle += 30) { // different angles for lines of firework
firework.lines.push({
angle: angle,
length: 10,
maxLength: random(50, 110)}); //varying length of lines
}
}
function showFirework(firework) {
R = random(10,250);
G = random(10,250);
B = random(10,250);
stroke(R,G,B);
strokeWeight(2);
fill(R,G,B);
if (!firework.isExploded) {
ellipse(firework.x, firework.y, firework.radius * 2, firework.radius * 2); //center of firework
}
else {
for (let i = 0; i < firework.lines.length; i++) {
//determining end point of line using angle and length
const xEnd =
firework.x +
cos(radians(firework.lines[i].angle)) * firework.lines[i].length; //polar coordinates
const yEnd =
firework.y +
sin(radians(firework.lines[i].angle)) * firework.lines[i].length;
line(firework.x, firework.y, xEnd, yEnd);
}
}
}