I wrote a fireworks program in P5JS

Demo

The Particle class

Basically, a particle has some physical properties: size (radius if consider it is a spherical object), color, mass (determinded by its size), position, velocity, and accelerator.

For each turn of graphic loop, we call the particle.update() function to update its velocity, and position.

update() {
        this.vx += this.ax * this.radius;
        this.vy += this.ay * this.radius;
        this.x += this.vx;
        this.y += this.vy;
        this.ax = 0;
        this.ay = 0;
        // increase life counter
        this.life++;        
}

We can also apply a force vector f(fx, fy) into the particle. This essentially adds a force f into the accelerator of the particle.

addForce(f) {
        this.ax += f.x;
        this.ay += f.y;        
}

There’s a special information that is the lifetime of a particle defined by a pair of variables: life (the counter) and the maxLife (limit). Each time the particle is updated, the counter will increase until it exceeds the maxLife, it will be removed from the memory.

Then, we draw it onto the screen as an ellipse fillled with its color and accordant position.

draw() {
        fill(this.color);
        noStroke();
        ellipse(this.x, this.y, this.radius, this.radius);        
    }

The Fireworks class

The constructor requires 2 variables:

  • nParticles - Number of particles

  • particles - The list to store all particles.

A function explode(x, y) indicates where to explosion willl be. Once this function is called, all particles will be initialized and stored into the fireworks.particles variable as those steps below:

  • Set the positions of all particles right at the position of the explosion

  • Set a random color for the particle

  • Add a random force to the particle

  • Store it to the list

explode(x, y) {
        for (let i = 0; i < this.nParticles; i++) {
            let p = new Particle(x, y, color(random(255), random(255), random(255)), random(2, 4));
            p.addForce(createVector(random(-1.0, 1.0), random(-1.0, 1.0)));
            this.particles.push(p);
        }
    }

An update() function to update all particles states.

update() {
        for (let i = 0; i < this.particles.length; i++) {
            //add gravity ==> remember this! other wise your particles won't fall
            this.particles[i].addForce(createVector(0, 0.03));
            // update and check if particle is dead
            this.particles[i].update();
            if (this.particles[i].life >= this.particles[i].maxLife) {
                this.particles.splice(i, 1);
                i--;
            }         
        }
    }

Finally, draw() all particles in the list:

draw() {
        this.update();
        for (let i = 0; i < this.particles.length; i++) {
            this.particles[i].draw();
        }
    }

That’s it!

Enjoy the fireworks!