Little Fortune Planet Breakdown - Part 2: Gravity of the simulation, man!

We're eager to get started after several hours of Part 1: Brainstorming so lets consider what it takes to simulate a world in an Entity-component system (ECS)?

Developers starting with ECS typically struggle what to implement as entities, and what to exclude.

We could simulate each particle with an entity and use a physics engine, but since we’d have to check neighboring cells constantly and we’d lose a lot of time understanding a third party physics engine, a simple two dimensional array feels a lot less risky. The grid size is static, which means no real lifecycle management is necessary.

Our world simulation system iterates over each cell, passing cell state to a behavior subsystem for magma, air, dirt, etc, and apply changes in a second pass. Subsystems add modularity in exchange for a small performance hit.

But since most simulation requires some gravity, we first need to figure out what direction is ‘down’ for each location. Calculating gravity live for 250000+ cells could become a bit of a performance problem, so instead we could precalculate a 2d array mask with the direction of the core of the planet. A bit premature perhaps, but with limited time got to go with the guts!

image15.png

Initial naive solution we could calculate the direct angle by subtracting each cell x,y coordinates from the planet center, and determining the angle of the resulting vector. In effect, we end up with a grid of ‘downward’ directions. So let's run it:

image5.gif

Uh-oh. The planet ended up as a octagon.

We end up with 8 Intercardinal sectors making gravity direction (for example) always left in the right section, while if you’d draw a pixel line from a cell to the core it might go left left, up, left left, up. Sort of like what you would get with Bresenham's line algorithm.

832px-Bresenham.svg.png

Since we basically want things to fall from circumference of the planet to the center, why don’t we draw loads of lines using the Bresenham's line algorithm from core to circumference and use each previous pixel as the direction of gravity?

image16.png

We end up with this:

image20.gif

A lot better! It’s worth getting quick-and-dirty when not too mathematically inclined.

Now we have gravity, we can move on to simulating something interesting!

Read part 3: Simulation time or play it here!