Simulating Universal Gravitation with SpriteKit
Gravity in SpriteKit, as with Box2D that it’s (apparently) built on or any other 2D physics enging you’ve likely come across is a single planet sort of gravity. By that I mean that it applies a single force to all bodies in the simulation - basically everything falls down. But what if you wanted a mutliple planet sort of gravity, can that be achieved in SpriteKit?
The answer is yes, and it turns out it’s quite simple to get some fun and quite realistic results.
In this simple SpriteKit app, tapping on the screen creates a new ‘planet’.
So how’s it done?
Very simply, we turn off gravity as it normally applies in a SpriteKit scene and we apply Newton’s law of universal gravitation to all the nodes in the physics simulation on every tick.
That is for every pair of nodes, apply a force to each one that is equal to the product of their masses (and the universal gravitational constant), divided by the distance between them, squared.
All the code you need to recreate the scene above is available on github.com/mbehan/fgmmr. There are some tweaks to the above formula to make the numbers a bit easier to deal with (i.e. smaller) and to make creating stable systems a bit easier, but sticking exactly to the formula above and plugging in some realistic numbers things work pretty much as you’d expect. The one surprise is that more often than not planets in stable systems have orbits that trace the shape of a propellar rather than straightforward repeating eliptical orbits (play around with it and you’ll see what I mean). I’m not sure if this is a result of an error in my code, the kinds of numbers I’m using or something else, perhaps it’s how the force is applied by the physics engine.
In addition to simulating gravity, I’m also combining planets that pass close to each other and adding trails to trace their paths and giving new planets random colour. It all results in a surprisingly fun and addictive little toy so even if you’re not interested in the code just build and run it on your iPhone and enjoy!