Look at them go!

Continuing with my attempt to learn Rust, I wanted to try building something more graphical. Inspired by a screensaver I saw many years ago (xscreensaver’s grav to be specific), I tried my hand at making a simple 2D orbit system using newtonian physics (or a close enough approximation, at least).

This system has one or more “planets”, which are fixed in place, and a number of “satellites” which orbit them. The satellites leave trails behind them, which lets us keep track of their motion.

You can find the source code and binaries by checking out the repo!

# Implementation

We can have multiple planets as well to get some funky patterns

As in my post on data-matrix, I’m not going to fully explain the implementation here but I’ll try to explain how some of the important components worked. Check out the repo for the full source code.

At its core, we are simply implementing the following equations:

$F = \frac{GMm}{r^2}$ $F = ma$

By simplifying these, we get the following:

$a = \frac{GM}{r^2}$

So at each timestep we set the acceleration of the satellite to $$M/r^2$$ multiplied by some constant, and update its velocity and position accordingly.

We used the Piston game engine to handle drawing, which provides us with some handy functions for creating windows, separating update and draw cycles, and generally abstracting away a lot of the pain of writing in raw OpenGL. With Piston we have an update loop, in which we update the acceleration/velocity/position of all the satellites, update the trails by recording the latest position and discarding the oldest position, and remove any satellites which have passed outside the screen or collided with a planet. At this point we also generate new satellites with a small probability. In the draw loop we simply draw a circle for each planet and satellite, and a series of line segments for each satellite’s trail.