The Code

To simulate the effect of a 3D starfield, we initially create a list of stars that are randomly positioned in the world. Each star is represented as a 3D coordinate, I mean, for each star we just store its X,Y and Z coordinates. Then we start the animation loop where we decrease the star’s Z coordinates on each frame. Decreasing the Z coordinate of a star makes it appear to be approaching the screen. When a star disappears from the screen, we reposition it again in the screen giving it random X and Y coordinates, and setting Z = maximum depth.

To make it even more interesting, we make closer stars bigger than distant stars. Similarly, we make closer stars brighter than the distant ones.

Since the stars are represented as 3D coordinates, they must be converted to 2D before being drawn into the screen. The code does that using perspective projection formulas.

The code is presented below. As you can see, the simulation is made with very few lines of code. If you have any doubt or suggestion, please don’t hesitate to leave a comment.