Newtonian gravity is way cool. So, cool that I will show you how you can make your own HTML5 canvas game simulating gravity. Don’t worry it won’t be hard. I will write down every step which is needed for our game.

It should be noted, that HTML5 is not a really new technology, but the canvas might still not work everywhere as expected (blame IE).

function gravitateTo(planet, obj) {
  var r   = planet.pos.distanceTo(obj.pos),
      f   = (planet.mass*obj.mass)/(r*r),
      phi = obj.pos.angleTo(planet.pos);

  obj.gravity.setPolar(phi, f);
  return gravity;

Vector basics

The game that we will write, needs a way to represent forces: velocity, acceleration and etc. The tool that we need is vectors.

I won’t really get into the vector basics, you must already be familiar with the easy stuff:

  • vector addition (therefore substitution)
  • multiplication (and division)
  • scaling (multipling a vector with a scalar number)

We will need some more than that, but this is the basics.

Check out the Jekyll docs for more info on how to get the most out of Jekyll. File all bugs/feature requests at Jekyll’s GitHub repo. If you have questions, you can ask them on Jekyll Talk.