Gravity — Javascript Universe

Back in 2001, after an idle browse I wrote a basic javascript universe that animating images around the screen, with respect to their gravitational influences on each other. The code is now long lost but I was recently reminded of it while thinking of ideas for mobile phone games. So here’s my recreation.

We'll need some particles that have size, position & velocity. Velocity (which is speed in a given direction) will be represented with an x and y speed giving us the direction and overall speed.

Now we need to set up a recurring loop to keep track of all of the particles and to move them to their new positions. This loop will be responsible for;

  • Updating the particles velocities dependent on their influences.
  • Applying the particles velocities to their position (i.e. moving them).
  • Re-drawing the canvas.

We can do this using the window.setInterval() method as follows;

Note: The interval here is set for 15 times a second regardless of your frame rate. In this example increasing or decreasing this will directly affect the speed at which the particles move. This can be fixed by introducing the concept of Game Time which I'll discuss later.

For drawing we'll simply use the canvas’ arc method to render a circle or ellipse.

To update a particle we'll calculate any velocity changes using “Newton’s Law of Universal Gravitation”.
F = G x ((m1 x m2) / r2)

In order to do so we'll need to know a particles mass and the distance between it and the influencing particles, which we can calculate using “Pythagoras theorem”.
a2 + b2 = c2

This will give us an attraction in a specific direction, i.e. towards the influencing particle. Which we can split into its x and y components using trigonometry.

Then it’s a simple case of updating the particles velocity with the force of attraction.

--

--

http://infectiousgr.in

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store