![Search icon](https://hackernoon.imgix.net/search-new.png?w=19&h=19)
In this article, I will describe the process of creating a Solar System in JavaScript using the Three.js library.
Firstly, we need to create the structure of the application. In order to focus on the 3D graphics and not the build or other attributes of modern applications, we will make the index.html
, add Three.js via cdn, and create a #root
element, which will be our scene.
Secondly, we will use CSS to stretch the #root
element on full screen.
Thirdly, we need to store the textures for the objects, so I created a directory /textures
. In order for the browser to access the textures, you can use a local server to view the index.html
.
In Three.js, to display, see and visualize something, we need a scene, a camera, and a visualization tool:
We could simply use a texture to draw the stars, but we can solve this problem in an elegant way by:
We will create entities using the static method createObject
for a class ObjectGroup
. The static method allows it to call itself without creating an instance of the class (this will be useful for creating the Sun, for example). So, we pass the texture's name and geometry to it and return a mesh with specific geometry and specific material we will add to the scene:
The ObjectGroup
class also has a constructor. But why do we need two functions when we can make do with one? The point is that you can build a system using absolute or relative coordinates. In general, we on Earth live in relative coordinates because we don't think about the speed at which we rotate around the Sun. To avoid doing all the rotation maths for planets that are associated with other entities (like the Earth's Moon or Saturn's rings), we need to get a group of objects that are in the same coordinate system. We will return this group of objects from the constructor and add the group to the Sun's coordinate system:
To change the properties of planets outside the class, we should add this group to the Map
collection when creating a group of planets:
Our system will rotate around the Sun, as it should, at a speed relative to that of the Earth.
const EARTH_YEAR = (2 * Math.PI) / 365
We need to change the rotation parameter while the application is running, so the code below needs to go through an animation loop:
Let's add two light sources. AmbientLight
will illuminate the entire scene regardless of the position of the objects, while PointLight
will be placed at the center of the scene inside the Sun, thereby simulating sunlight:
All we have to do now is to start the render cycle:
Congratulations! You have created a solar system using Three.js. It's simple, but we all have to start somewhere, and in this application, we've got the basics of 3D figured out.
The full code is available on GitHub.