Celestial bodies

Small creative coding piece simulating objects in space orbiting around a single sun

Celestial bodies

I wrote this sketch in 2022 from the comfort of my quarantine hotel.

It shows a common orbital mechanics implementation, simulating bodies in space orbiting around a single sun. I thought it would be cool to generate everything from scratch, including the background texture of the sky and the stars.

Creating the night sky texture

The background texture is based on a simple perlin noise map

Here's the pseudo-code to generate it:

for (let x = 0; x < width; ++x) {
  for (let y = 0; y < height; ++y) {
    const color = lerpColor(
      startColor,
      endColor,
      noise(x / 300, y / 300)
    );
    setPixel(col)
  }
}

Now swap the colours for something a bit more spacey I used:

startColor = color('#000000');
endColor = color('#030C34');
Perlin noise map with night sky colors

For the stars, the only trick was finding the right number of stars, one that would scale nicely regardless of the texture size, and the right colours. After doing some colour picking online I came up with the following values:

const pixelCount = width * height;
const starCount = random(pixelCount * 0.001, pixelCount * 0.003);

starColors = [
  color('#9bb0ff'),
  color('#aabfff'),
  color('#cad7ff'),
  color('#f8f7ff'),
  color('#fff4ea'),
  color('#ffd2a1'),
  color('#ffcc6f')
];

We were left with the following:

The gravity