N-body simulations with Unity

3 minute read Published:

Using the Unity game engine to simulate a simple solar system with N-body simulations.

On our quest to discover more about space, our solar system, and the universe, we’ve looked at what N-body simulations do, and how they can help us understand some of the forces at play in the universe.

n-body simulation in unity game engine

An n-body simulation in one sense is a mathematical model of a grouping of objects under the influence of a force such as gravity. The simulation we’ve constructed in the Unity game engine is that of a simple single star system with a small grouping of planets and moons.

To build it, we used a 3D skybox of a space scene as the back drop and have a series of scripts that simulate the forces using a fixed time step in Unity. Each ‘body’ in the simulation has a mass on it’s Physics RigidBody component based on it’s size (radius), and surface gravity value. Velocity is calculated from acceleration relative to other bodies in the simulation.

To move each body in the simulation, their calculated velocity values are added to the position of the bodies multiplied by the fixed time step value that the simulation uses.

How fast can we simulate with N-body simuations on a computer? The computer hardware we use dictates the speed at which we can run the simulation, along with a couple of other factors: - The number of objects in the simulation (the "N" in "N-body") - The time step value used for the simulation - The actual code for the simulation method, as well as the underlying engine (rendering, physics, etc...)

Once the simulation was setup, we could observe many interesting forces at play. It is super interesting to see how larger bodies in the simulation influence other, smaller bodies.

With a central star moving slowing along we observe most planets and moons orbiting around this central point. Smaller moons captured by planets generally follow those planets in their orbits.

If we wait long enough, we start to see interesting behaviours. For example, after a few orbits, this planet gathered enough momentum on an orbit pass to swing with a lot of acceleration around the central star. As it did so, it’s moon was flung out of it’s orbit and sent flying out of the ‘system’.

a moon breaking out of orbit

Another interesting interaction was that of two planets crossing paths after very long and wide orbits around the star. The larger red planet crossed paths with a slightly smaller blue planet, and as it did it significantly reshaped the blue planet’s orbit.

planets crossing orbit paths

The trajectory was quite drastically affected on the blue planet, while the red planet even had a small visible adjustment to it’s own path.

N-body simulations can be used to simulate many different particle systems and interactions, and don’t necessarily need to be all about gravity. There are many more use cases to explore here.