Interactive modelling with p5.js

2022-06-13

I worked a lot with particle models (molecular dynamics, agent-based models). In all those cases plotting is at times even more tedious than writing the simulation itself.

A nice tool to circumvent this issue in the prototyping stage is the javascript library p5js! Let’s dive straight into it.

First steps first: the model

Every simulation starts (hopefully) with a rough model in mind. Let’s simulate an apple falling down. The corresponding model is of course Newton’s second law

Example simulation with p5js

Below you can see a simple example for this model using p5js.

Click into the white area to add more apples. 1

How does it work?

For simplicity, we just simulate one apple. How many lines do we need for that, including the simulation and plotting?

With p5js, we need only 32 lines!2

First we define the objects we need.

let pv = p5.Vector;  // shortcut for using p5.Vector functions

let X, V, gravity;      // position, velocity and gravity
const R = 20;        // radius in pixel

For p5js we only need to define two functions: setup and draw. The setup function is called once in the beginning and the draw for each time-step. Easy!

The setup function in our case just initiated the initial position, velocity and a vector pointing downwards.

function setup() {
  createCanvas(240, 320);
  frameRate(30);

  X = createVector(width/2, height/4);
  V = createVector(0.0, 0.0);
  gravity = createVector(0.0, 0.001);
}

Finally, the draw function will draw the canvas white and iterate the symplectic Euler method 3

Then we ensure that the apple stays within the canvas4 and draw it.
function draw() {
  background(255,255,255);

  // symplectic Euler method
  V.add( pv.mult( gravity, deltaTime ) );
  X.add( pv.mult( V, deltaTime) );

  // keep apple above the ground
  if( X.y + R > height){
    X.y = height - R;
    V.y = 0.0;
  }

  // draw apple
  fill(200,50,50);
  noStroke();
  circle(X.x, X.y, 2*R);
}

Voila. That’s it! From here you could start to experiment with the simulation. For example using the online p5js-editor!

Challenge: Can you modify the example such that there are two falling apples?

You can find all available functions of p5js in the reference. For adding two apples you might want to use the p5.Vector.dist function.

If you want to read more on the numerical method, check out my project description about position-based dynamics.