Fragmented Notes

This is where I write about learning to code

A Minimalist Physics Engine

Daniel Shiffman surprised me yesterday in his course “The Nature of Code” with a most simple concept of a physics engine in two lines of JavaScript:

1
2
pos.add(vel);
vel.add(acc);

These two lines have the three components(vectors) that are necessary to describe movement: position, velocity and acceleration:

  1. Objects have a position (pos).
  2. The position gets changed (add) by velocity (vel).
  3. The velocity gets changed (add) by acceleration (acc).

The add-method comes from P5JS and belongs to the vector object.

Of course to use it in a sketch, there is more to write than these two lines, but they contain the core concept. For example, this code from the course creates a circle that looks like it is falling, because it accelerates downward:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function Walker(x,y) {
  this.pos = createVector(x,y);
  this.vel = createVector(0,0);
  this.acc = createVector(0,0.1);   

  this.update = function(){
      this.vel.add(this.acc);
      this.pos.add(this.vel);
  }

  this.display = function(){
      fill(255);
      ellipse(this.pos.x,this.pos.y,48,48);
  }
}