On this site you can play with ready-made simulations. In this guide we go one step further: you write the simulation yourself. Each lesson builds a simple version of one simulation in p5.js from scratch, explaining every line of code and the physics behind it. This way you learn physics and programming at the same time – and in the end you have a program you can change however you like.
if, functions. If p5.js is new to you, first read the introduction to p5.js.Almost every motion simulation has the same structure. In p5.js the function setup() runs once, at the start, and draw() about 60 times per second. So:
draw() time moves on by a small step dt, and we calculate the new velocity and position from a physical law.function draw() {
// 1. step: new velocity and new position from a physical law
v = v + a * dt;
x = x + v * dt;
// 2. drawing: metres → pixels
background(255);
circle(x * SCALE, 100, 20);
}
This way of calculating is called Euler's method. It is simple and accurate enough for most school examples; in later lessons you will see when something better is needed.
| # | lesson | what you learn | ready-made simulation |
|---|---|---|---|
| 1 | Free fall | state, time step dt, Euler's method, scale metres → pixels, comparison with the formula | free fall |
| 2 | Projectile motion | motion in two dimensions, velocity components, the trail of the path, the keyboard | projectile motion |
| 3 | Projectile with air resistance | a force that depends on velocity, objects, one function for two bodies | projectile with air resistance |
| 4 | Mass and spring | oscillations, plain Euler and Euler–Cromer, checking the energy | mass and spring |
| 5 | Simple pendulum | angle as the state, measuring the period, when the formula stops working | simple pendulum |
| 6 | Collisions | detecting a collision, conservation of momentum, coefficient of restitution | momentum and collisions |
| 7 | Kepler orbits | gravity as a vector, convenient units, checking Kepler's third law | Kepler's laws |
| 8 | Waves | sine in space and time, wave speed, superposition and standing waves | waves and sound |
| 9 | Refraction of light | the angle from the mouse position, Snell's law, total internal reflection | geometrical optics |
The same recipe works in any language. On svetprogramiranja.com there are lessons in Processing (Java and Python), for example projectile motion in Processing and the whole Processing programming guide.
The lessons are designed so that one fits into one lesson period: the first 10 minutes for the ready-made simulation and the physics, then writing the program together step by step in the p5.js editor, and finally independent tasks (changing the program). They suit computing, physics and project-based lessons.