Coding Assignment – Week #10

Concept:

I wanted to utilize this assignment for an exploration of physics principles, particularly focusing on forces and collision events inside a dynamic particle system. I started from the example 6.10: Collision Events by Daniel Shiffman, and added new elements and events.

The sketch:

Technical Implementation:

The sketch is implemented using the p5.js and Matter.js libraries. The p5.js library is responsible for the creation of the canvas, particle rendering, and overall animation loop, while Matter.js handles the physics engine, collision detection, and force application. The particles are randomly added to the system, and each of them undergoes a color change upon its first collision. Once the number of particles is divisible by 60,  explosive force is applied to randomly selected particles giving a more dynamic feel to the sketch by initiating a small explosion. Additionally, a boundary is added to the bottom, and the number of particles is constantly being updated by removing the particles that are pushed outside of the canvas.

Code:

The most interesting part of the code was the handleCollisions(events) function. It is triggered by collision events in the Matter.js physics engine. It iterates through the pairs of bodies involved in the collisions, extracting the corresponding particle instances associated with each body. This function handles color-changing behavior for both particles upon their initial collision. Additionally, it applies forces to each particle based on their velocities, amplifying the collision event.

// handling collisions between particles
function handleCollisions(event) {
  for (let pair of event.pairs) {
    let bodyA = pair.bodyA;
    let bodyB = pair.bodyB;

    let particleA = bodyA.plugin.particle;
    let particleB = bodyB.plugin.particle;

    if (particleA instanceof Particle && particleB instanceof Particle) {
      // changing colors upon first collision 
      particleA.change();
      particleB.change();

      // Applying a force when particles collide
      let forceMagnitude = 0.005;
      let forceA = Vector.mult(
        Vector.normalise(particleA.body.velocity),
        forceMagnitude
      );
      let forceB = Vector.mult(
        Vector.normalise(particleB.body.velocity),
        forceMagnitude
      );

      particleA.applyForce(forceA);
      particleB.applyForce(forceB);
    }
  }
}
Future Improvements:

For future improvements, it would be interesting to explore different shapes and how the collision events and forces would act on them. I like that the sketch is dynamic and develops over time, although perhaps there could be a more clear story behind it.

Leave a Reply

Your email address will not be published. Required fields are marked *