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.
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
Below you can see a simple example for this model using p5js.
Click into the white area to add more apples ๐. [1]
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 canvas[4] 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.
For the curious reader, to add more objects we need to deal with collisions. I used the Position-based dynamics method, you can read more about this method here and in the cited references therein. โฉ๏ธ
In case you are wondering: The full simulation shown above, with restart button and arbitray many apples, just needs 111 lines! โฉ๏ธ
The symplectic Euler method is preferable to the explicit or implicit Euler method here, as it will almost conserve the total energy of the system. โฉ๏ธ
The only small complication is that the point