Web Analytics
Kepler orbits in p5.js – gravity step by step

Kepler orbits in p5.js – gravity step by step

The seventh lesson of the guide Program a physics simulation. We give the program just one law – Newton's law of gravitation – and the initial position and velocity of a planet. From that, ellipses and all three of Kepler's laws appear “by themselves”. Change the initial speed with the ↑ and ↓ arrow keys (click the canvas first).

Physics: Kepler's laws – gravitation F ~ 1 / r², ellipses, the law of areas, T² = a³.

Programming: an acceleration vector towards a centre, several steps per frame, convenient units (AU and year), comparing a measurement with a law.

You should know: lessons 2 and 4 (projectile motion, Euler–Cromer).

Step 1: convenient units

Distances in metres and time in seconds would give huge numbers. So we use the astronomical unit (AU, the mean distance of the Earth from the Sun) and the year. In these units the Earth goes round the Sun on a circle of radius 1 in 1 year, at 2π AU/year, and for the Sun GM = 4π² AU³/year²:

const GM = 4 * Math.PI * Math.PI;  // the Sun: GM in AU³/year² (Math.PI: p5's PI does not exist yet when the file loads)
const dt = 0.002;        // time step, years
const STEPS = 10;        // steps per frame

A step of 0.002 years (about 17 hours) is small, so we do 10 steps in each frame – otherwise the planet would move too slowly.

Step 2: gravity as a vector

The force of gravity always points towards the Sun (at the origin) and weakens with the square of the distance. The acceleration has magnitude GM / r² and the direction opposite to the vector (x, y); so we get the components by dividing by r³:

const r = sqrt(x * x + y * y);
const ax = -GM * x / (r * r * r);          // gravity: towards the Sun, weakens as 1/r²
const ay = -GM * y / (r * r * r);
vx = vx + ax * dt;                         // Euler–Cromer
vy = vy + ay * dt;
x = x + vx * dt;
y = y + vy * dt;

Euler–Cromer from lesson 4 matters here: with plain Euler the orbit would widen into a spiral (task 3).

Step 3: the initial speed decides the orbit

The planet starts 1 AU from the Sun, moving perpendicular to the direction of the Sun. If its speed is exactly 2π AU/year, the orbit is a circle (the Earth). A smaller speed – the planet “falls” towards the Sun along an ellipse; a larger one – it moves away. The variable factor says how many times the speed is larger or smaller than the circular one:

vy = 2 * PI * factor;        // the speed of a circular orbit at 1 AU is 2π AU/year

Step 4: checking Kepler's third law

The program remembers the smallest and largest distance (perihelion and aphelion), calculates the semi-major axis a = (rmin + rmax) / 2 and the period from the third law T = a1.5. It measures the period as the time between two crossings of the positive x axis:

initial speeda (AU)T measuredT = a1.5
0.6 · circular0.6100.478 years0.476 years
0.8 · circular0.7350.631 years0.631 years
1.0 · circular1.0001.000 years1.000 years
1.2 · circular1.7862.387 years2.387 years

Nowhere does the program “know” Kepler's third law – it follows from the law of gravitation. That is exactly what Newton showed.

Whole program

Copy it into the p5.js editor and delete the line canvas.parent('lesson-canvas');.

// Kepler orbits – program from the lesson “Program a physics simulation” (simulacije.svetprogramiranja.com)
const GM = 4 * Math.PI * Math.PI;  // the Sun: GM in AU³/year² (Math.PI: p5's PI does not exist yet when the file loads)
const dt = 0.002;        // time step, years
const STEPS = 10;        // steps per frame

let factor = 0.8;        // initial speed compared with the speed of a circular orbit
let x, y, vx, vy, t;
let trail, lastCrossing, period, rMin, rMax, pixelsPerAU;

function setup() {
  const canvas = createCanvas(320, 360);
  canvas.parent('lesson-canvas');
  start();
}

function start() {
  x = 1;                       // the planet starts 1 AU from the Sun
  y = 0;
  vx = 0;
  vy = 2 * PI * factor;        // the speed of a circular orbit at 1 AU is 2π AU/year
  t = 0;
  trail = [];
  lastCrossing = 0;
  period = null;
  rMin = 1;
  rMax = 1;
  const a = 1 / (2 - factor * factor);       // semi-major axis (from conservation of energy)
  pixelsPerAU = 130 / max(1, 2 * a - 1);           // so that the whole orbit fits on the canvas
}

function step() {
  const r = sqrt(x * x + y * y);
  const ax = -GM * x / (r * r * r);          // gravity: towards the Sun, weakens as 1/r²
  const ay = -GM * y / (r * r * r);
  vx = vx + ax * dt;                         // Euler–Cromer
  vy = vy + ay * dt;
  const oldY = y;
  x = x + vx * dt;
  y = y + vy * dt;
  t = t + dt;
  rMin = min(rMin, sqrt(x * x + y * y));
  rMax = max(rMax, sqrt(x * x + y * y));
  // the planet crosses the positive x axis (upwards): one orbit is complete
  if (oldY < 0 && y >= 0 && x > 0) {
    const tCross = t - dt * y / (y - oldY);
    period = tCross - lastCrossing;
    lastCrossing = tCross;
  }
}

function draw() {
  background(11, 19, 36);
  for (let i = 0; i < STEPS; i++) {
    step();
  }
  trail.push([x, y]);
  if (trail.length > 3000) {
    trail.shift();
  }

  // the Sun, the path and the planet (y upwards)
  const sx = 175;
  const sy = 200;
  noStroke();
  fill(250, 204, 21);
  circle(sx, sy, 18);
  noFill();
  stroke(71, 85, 105);
  strokeWeight(1);
  beginShape();
  for (const point of trail) {
    vertex(sx + point[0] * pixelsPerAU, sy - point[1] * pixelsPerAU);
  }
  endShape();
  noStroke();
  fill(96, 165, 250);
  circle(sx + x * pixelsPerAU, sy - y * pixelsPerAU, 12);

  // numbers
  const a = (rMin + rMax) / 2;
  fill(226, 232, 240);
  textSize(13);
  text('initial speed = ' + factor.toFixed(1) + ' · circular (↑ ↓)', 10, 20);
  text('T measured = ' + (period === null ? '…' : period.toFixed(3) + ' years'), 10, 40);
  text('a = (rmin + rmax) / 2 = ' + a.toFixed(3) + ' AU', 10, 60);
  text('T = a^1.5 = ' + pow(a, 1.5).toFixed(3) + ' years', 10, 80);
}

function keyPressed() {
  if (keyCode === UP_ARROW && factor < 1.25) {
    factor = factor + 0.1;
    start();
    return false;
  }
  if (keyCode === DOWN_ARROW && factor > 0.55) {
    factor = factor - 0.1;
    start();
    return false;
  }
}

Tasks for you

  1. Print the current speed of the planet in km/s (1 AU/year ≈ 4.74 km/s). Where is the planet fastest?
    Solution

    text('v = ' + (sqrt(vx * vx + vy * vy) * 4.74).toFixed(1) + ' km/s', 10, 100); For an initial speed of 0.8 · circular the planet has 23.8 km/s at aphelion (1 AU) and 50.6 km/s at perihelion (0.47 AU) – Kepler's second law: it is fastest closest to the Sun.

  2. What happens at an initial speed √2 ≈ 1.41 times the circular one? (Change the limit in keyPressed or set factor = 1.42.)
    Solution

    The planet leaves the Solar System: this is the escape velocity. The path is no longer an ellipse, but a parabola or a hyperbola.

  3. Replace Euler–Cromer with plain Euler (position first, from the old velocity). What happens to the circular orbit?
    Solution

    The orbit widens into a spiral: after 5 years the largest distance is 1.51 AU, and after 20 years 2.19 AU. The energy of the planet grows – the same problem as with the spring.

  4. Add a second planet with a different initial speed (e.g. as an object, as in the lesson on air resistance) and compare their periods.
    Solution

    Write a function newPlanet(factor) that returns an object {x, y, vx, vy}, and a function step(planet). The planets do not attract each other – only the Sun attracts them, so each has its own period according to T = a1.5.

Next