The second lesson of the guide Program a physics simulation. In the first lesson the body moved only downwards. Now we throw it at an angle: it moves forwards and up and down, so we track two coordinates. Change the angle with the ↑ and ↓ arrow keys (click the canvas first), and click the canvas to throw again.
Physics: projectile motion – uniform horizontal motion and vertical motion under gravity.
Programming: velocity components, sin and cos, an array of points (trail), beginShape(), the keyboard (keyPressed).
You should know: lesson 1 (free fall).
A body thrown with speed v0 at an angle α moves forwards with velocity vx and upwards with velocity vy at the same time:
vx = v₀ · cos α vy = v₀ · sin α
The functions sin() and cos() in p5.js work with angles in radians, so we convert degrees with the function radians():
function start() {
const a = radians(angle);
x = 0;
y = 0;
vx = v0 * cos(a); // horizontal component of velocity
vy = v0 * sin(a); // vertical component (positive upwards)
t = 0;
flying = true;
trail = [];
}
This time y grows upwards (as in physics), and we flip it into pixels when drawing.
No force acts horizontally, so vx does not change. Vertically gravity acts, so vy decreases by g · dt in every step – just like in free fall:
vy = vy - g * dt; // only the vertical velocity changes
x = x + vx * dt;
y = y + vy * dt;
t = t + dt;
That is all the physics of projectile motion: two independent motions happening at the same time.
To see the parabola, we store every position in the array trail (in each step we add one pair [x, y] with push), and then
join them with a line using beginShape(), vertex() and endShape():
trail.push([x, y]);
// ...
beginShape();
for (const point of trail) {
vertex(x0 + point[0] * SCALE, groundY - point[1] * SCALE);
}
endShape();
We subtract the height in metres from the position of the ground because y on the canvas grows downwards.
p5.js calls the function keyPressed() when you press a key, and keyCode tells which one. On the up arrow the angle increases by 5° and the body is thrown again.
return false stops the arrow key from scrolling the page.
function keyPressed() {
if (keyCode === UP_ARROW && angle < 85) {
angle = angle + 5;
start();
return false; // the arrow key does not scroll the page
}
// the same for DOWN_ARROW
}
When the body lands, the program prints the range from the simulation and the range from the formula R = v₀² · sin 2α / g. For v0 = 20 m/s and α = 45° the simulation gives 40.5 m, and the formula 40.8 m. The 0.3 m difference comes from the step dt = 1/60 s: Euler's method “cuts the corner” a little. With a step ten times smaller the simulation gives 40.75 m.
Copy it into the p5.js editor and delete the line canvas.parent('lesson-canvas');.
// Projectile motion – program from the lesson “Program a physics simulation” (simulacije.svetprogramiranja.com)
const g = 9.81; // acceleration due to gravity, m/s²
const v0 = 20; // initial speed, m/s
const SCALE = 7; // how many pixels make one metre
const dt = 1 / 60; // time step, s
let angle = 45; // launch angle, in degrees
let x, y, vx, vy, t, flying;
let trail = []; // points of the path
function setup() {
const canvas = createCanvas(320, 300);
canvas.parent('lesson-canvas');
start();
}
function start() {
const a = radians(angle);
x = 0;
y = 0;
vx = v0 * cos(a); // horizontal component of velocity
vy = v0 * sin(a); // vertical component (positive upwards)
t = 0;
flying = true;
trail = [];
}
function draw() {
background(248, 250, 252);
if (flying) {
vy = vy - g * dt; // only the vertical velocity changes
x = x + vx * dt;
y = y + vy * dt;
t = t + dt;
if (y <= 0) { // the body has hit the ground
y = 0;
flying = false;
}
trail.push([x, y]);
}
// ground
const groundY = height - 30;
const x0 = 15;
stroke(51, 65, 85);
strokeWeight(3);
line(0, groundY, width, groundY);
// path: metres → pixels
noFill();
stroke(59, 130, 246);
strokeWeight(2);
beginShape();
for (const point of trail) {
vertex(x0 + point[0] * SCALE, groundY - point[1] * SCALE);
}
endShape();
// body
noStroke();
fill(249, 115, 22);
circle(x0 + x * SCALE, groundY - y * SCALE, 14);
// numbers
fill(11, 19, 36);
textSize(14);
text('angle = ' + angle + '° (arrows ↑ ↓)', 10, 22);
text('t = ' + t.toFixed(2) + ' s, x = ' + x.toFixed(1) + ' m', 10, 42);
if (!flying) {
const R = v0 * v0 * sin(radians(2 * angle)) / g;
text('range: ' + x.toFixed(1) + ' m', 10, 62);
text('formula: ' + R.toFixed(1) + ' m', 10, 82);
}
}
function keyPressed() {
if (keyCode === UP_ARROW && angle < 85) {
angle = angle + 5;
start();
return false; // the arrow key does not scroll the page
}
if (keyCode === DOWN_ARROW && angle > 5) {
angle = angle - 5;
start();
return false;
}
}
function mousePressed() {
if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
start();
}
}
Both angles give 35.2 m. Angles that add up to 90° have the same range, because sin 60° = sin 120°. The largest range is at 45°.
The simulation gives 10.08 m, and the formula H = v₀² · sin² α / (2g) ≈ 10.19 m.
let yMax = 0; // in start(): yMax = 0;
// in draw(), after calculating the new y:
if (y > yMax) {
yMax = y;
}
text('maximum height: ' + yMax.toFixed(2) + ' m', 10, 102);The range is about 247 m (simulation 246.8 m), so the scale must be about 1 pixel per metre: SCALE = 1.15.
For example line(px, py, px + vx * 3, py - vy * 3), where px and py are the coordinates of the body in pixels. The horizontal part of the vector stays the same, while the vertical part gets smaller, is zero at the highest point and then grows downwards.