Simulating Multiple Sources of Gravity in Box2D

Simulating a single source of gravity is a sinch in  Box2D. You can even switch gravity off if you like. But what about simulating multiple gravity sources, like planets? This isn’t as hard as it sounds, but requires some additional work. Something to consider is that when simulating radial gravity, or planet gravity, we don’t work with the same scales as in, um, the universe. Instead of orbits that are thousands kilometers we’re working with ten to fifty meters, depending on the canvas size and pixel to meter ratio you are using.

The example below has two different gravity sources, lets refer to them as planets. The planets are different in size, the reach of each respective gravitational field is different, and the strength of gravity is defined per planet. The further away from the planets center, the weaker the gravitational pull. Once outside of the gravity field, bodies will not experience the pull of gravity.

Create debris in the example by pressing the mouse on the canvas, holding the mouse button down, move the pointer in the direction you want to fire the debris. Let go of the mouse button to fire the debris. The red line indicates the magnitude of the linear velocity of the debris. The blue lines indicate the magnitude of the gravitational pull.



This is how it works.

  1. Create the planets. The planets are static bodies with a given position, radius, gravity factor (used to determine the size of the field of gravity), and gravity. The last three values are stored as user data for easy access later.
  2. Loop through entities, referred to in the code as debris, that should be impacted by gravity. The loop should check if the distance between the debris and a planet is within the planets gravity field. If this is the case, apply a gravitational force proportional to the square of the distance between the debris and the planet.

Download the code:  gravity.js (472 downloads)