The inspiration I get is from fireworks. I want to draw several particles that diffuse when the mouse is clicked to simulate fireworks.
https://editor.p5js.org/HanBao/full/4WmI5m-l8
Today, I’ll talk about the design and logic behind my interactive fireworks simulation. The inspiration for this project comes from real-world fireworks, and I wanted to recreate that experience using code, allowing particles to diffuse when the mouse is clicked, just like fireworks in the sky.
At the beginning, I create a canvas of 600 by 600 pixels where the entire simulation will take place. I also define a fireworks array, which will store multiple firework objects, and a speed variable to control the movement of the particles. This is essential to ensure the particles have a smooth and controlled motion as they spread out.
let fireworks = [];
let speed = 4;
function setup() {
createCanvas(600, 600);
}
I’ve created a class called Firework which is responsible for the creation, update, and display of each firework. When a firework is generated, it has multiple particles that move outward in all directions. Inside the constructor of the Firework class, I initialize the starting position, a randomly generated color, a radius that controls how far the particles can spread, and a set of particles, each with its own angle to ensure they spread out evenly.
class Firework {
constructor(startX, startY, count, radius) {
this.startX = startX;
this.startY = startY;
this.x = startX;
this.y = startY;
this.color = [random(0, 255), random(0, 255), random(0, 255)];
this.radius = radius;
this.speed = speed;
this.particles = [];
this.finished = false; // Initialize as "not finished"
This is calculated using the formula 360 / count so that particles are evenly distributed in a circular manner.
for (let i = 0; i < count; i++) {
let angle = radians(i * (360 / count));
this.particles.push({ x: this.x, y: this.y, angle: angle });
}
The update method in the Firework class handles the movement of the particles. Using cos and sin functions, I adjust the x and y coordinates of each particle based on the angle calculated earlier. This makes the particles move outward, creating the burst effect.
update() {
for (let particle of this.particles) {
particle.x += this.speed * cos(particle.angle);
particle.y += this.speed * sin(particle.angle);
}
}
Draws each particle as a small ellipse on the canvas.
display() {
for (let particle of this.particles) {
fill(this.color);
noStroke();
ellipse(particle.x, particle.y, 5, 5);
}
}
}
function draw() {
background(0);
// Access the current firework object
for (let i = 0; i < fireworks.length; i++) {
let firework = fireworks[i];
firework.update();
firework.display();