Jason's notes

Week2 Vectors

For this week’s assignment, I created a particle system where planet/particle movements are been affected by each other. Try it below, or on p5.js editor

Particle system simulator

The forces are calculated with a simple formula that they are stronger when the distance between two particles is bigger. This is not exactly the gravitation force between planets, since another version I did with the Newton’s law seems pretty chaotic and planets can easily be going outside the canvas.

This is the way I did the force calculation: the forth is depending on the two particles mass and the distance between them. I also add a force towards the center so every particles can be pull to the center and remain in the canvas.

this.acc.set(0, 0);

// add force between planets
otherPlanets.forEach(planet => {
  const v = p5.Vector.sub(planet.pos, this.pos)
  this.acc.add(v.setMag(0.1 * this.mass * planet.mass));
})

// add force towards the center
const center = new p5.Vector(width / 2, height / 2);
this.acc.add(p5.Vector.sub(center, this.pos).setMag(0.2 * this.mass))

A problem I met was that two particles acted differently even if they are in the same situation. One thing came in to my mind is the sequence of the calculation. I realized that I should do all the force calculation at first and then do the update and drawing. Fortunately, it worked!

// (Wrong) Before: add forces while do the position update
planets.forEach((planet, index) => {
  planet.addForce(planets.filter((_, i) => (i !== index)));
  planet.update();
  planet.draw();
})

// After: add forces togather at first
planets.forEach((planet, index) => {
  planet.addForce(planets.filter((_, i) => (i !== index)));
})

planets.forEach((planet) => {
  planet.update();
  planet.draw();
})

Here is a demo video. Particles will finally become this organic shape which is pretty interesting. It also make sense that smaller particles with smaller mass ended up having a bigger rotating radius.