I am embarking on my first project using three.js to create a miniature solar system consisting of 1 star, 2 planets, and 1 moon orbiting each planet. As a beginner to both three.js and JavaScript in general, I am eager to learn.
Currently, I have successfully built the static system with the Sun, Mars, Phobos, Earth, and the Moon.
However, I am facing a challenge in figuring out how to make the planets orbit around the Sun and the moons orbit around their respective planets.
Here is a glimpse of what I have accomplished so far:
//declaration of global variables
function init(){
/*initializing code: setting up cameras, declaring variables, and more*/
function celestialBodiesSetup(){
var geometry, material, image;
var celestialBodies=[sun, mars, phobos, earth, moon];
//sun, mars, etc. are defined as global variables before the init function
for(var i=0; i < celestialBodies.length; i++){
switch (celestialBodies[i]){
case sun:
material = new THREE.MeshPhongMaterial();
geometry = new THREE.SphereGeometry(35, 32, 32);
image = "mysun.png";
sun = createSphere(geometry, material, image);
sun.position.set(0, 0, 20);
var pointLight = new THREE.PointLight(0xFDFDFD, 2, 1800, 70);
sun.add(pointLight);
break;
case mars:
material = new THREE.MeshPhongMaterial();
geometry = new THREE.SphereGeometry(17, 32, 32);
image = "mars.jpg";
mars = createSphere(geometry, material, image, sun);
mars.position.set(150, -15, 0);
break;
/*repeat the process for the remaining celestial bodies*/
function createSphere(geometry, material, image, celBody){
var sphere = new THREE.Mesh(geometry, material);
material.map = THREE.ImageUtils.loadTexture(image);
if(celBody) celBody.add(sphere);
else scene.add(sphere);
return sphere;
}
celestialBodiesSetup();
}
Now, my next step is to work on the animate() function, but I am uncertain about vectors, rotations, and other aspects.
Currently, my knowledge is limited to basic rotations like earth.rotation.y += 0.1 to make the planet rotate on its axis.