This is a p5.js sketch inspired by the Coding Train’s Coding Challenge #7 of creating a Solar System.

screenshot-01

It makes use of Newton’s Law of Gravitation:

F = G * m1 * m2 / (r * r)

Implemented as follows (making use of the p5.js Vector object):

// points from Obj1 => Obj2
static forceDueToG(obj1, obj2){
  // Gravitational Force: F = G * m1 * m2 / (r * r)
  let r = p5.Vector.sub(obj2.pos, obj1.pos);
  let rSquared = r.magSq();
  let forceMag = Physics.G_ADJUSTED * obj1.mass * obj2.mass / rSquared;
  let force = r.setMag(forceMag);
  return force;
}

Additionally, it uses values for Mass and Radii based on actual values for the masses of the planets in our solar system.

And, after randomly placing the masses, it determines what their approximate orbital velocity based by determining the speed that would generate a Centripetal Force equal to the gravitational force at that distance.

static orbitalV(ofObject, aroundObj){
  // From balancing:
  // Gravitational Force: F = G * m1 * m2 / (r * r)
  // Centripetial Force: F = m * v * v / r
  // solving for speed of obj1: v = sqrt( G * m2 / r)
  let r = p5.Vector.sub(aroundObj.pos, ofObject.pos);
  let speed = pow(Physics.G_ADJUSTED * aroundObj.mass / r.mag() , 0.5);
  let v = r.copy();
  v.rotate(HALF_PI);
  v.setMag(speed);
  return v;
}

Caveat: The objects only experience the gravitational attraction of the “sun” at the center; which in turn does not experience any gravitational force. This allows for a stable system, but lacks the interplay of forces in a true n-body simulation.

Controls

(No interactivity implemented yet).

References:

Links: