Explore the wonders of our solar system using three.js!

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.

Answer №1

If you're looking for some exciting projects to try out, check out the

100000 Stars case study

There are plenty of examples to explore on the

Chrome Experiments site

For a great introduction to the threejs library, dive into the sample visualizations on

stemkoski.github.io/Three.js

And don't miss out on exploring the Earth model at

mrdoob.github.io/three.js

Take your project to the next level by learning about rotation vectors, quaternions, and shaders through various tutorials like

oos.moxiecode.com

If you're in need of a quick prototype, consider using the Unity 3D engine for a demonstration overnight.

Answer №2

I replicated a similar action and successfully achieved the rotations and orbits using the code below:

//Earth rotation and orbit
earthMesh.rotation.y = Date.now() * -0.001;
earthMesh.position.x = Math.sin( Date.now() * 0.001 ) * 219.15;
earthMesh.position.z = Math.cos( Date.now() * 0.001 ) * 219.15;

//Moon rotation and orbit
moonMesh.rotation.y = Date.now() * -0.001;
moonMesh.position.x = Math.sin( Date.now() * 0.001 ) * 219.15 + Math.cos( Date.now() * -0.007 ) * -10;
moonMesh.position.z = Math.cos( Date.now() * 0.001 ) * 219.15 + Math.sin( Date.now() * -0.007 ) * -10;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn the process of connecting checkboxes to a database in MeanStack using Angular

Hey everyone, I'm currently working with AngularJS ng-repeat and I am trying to dynamically bind a checkbox based on a true or false value from the database. However, even when the database value is set to true, the checkbox does not automatically che ...

Text transitions in a gentle fade effect, appearing and disappearing with each change

I want to create a smooth fade in and out effect for the text within a div when it changes or hides. After researching on Google and Stack Overflow, I found that most solutions involve adding a 'hide' CSS class and toggling it with a custom func ...

An async function cannot be used as a Constructor

I am in the process of creating a constructor function using JavaScript. This constructor needs to be asynchronous because I am utilizing the Phantom JS module for data scraping. As a result, an asynchronous function must be used to scrape data through Pha ...

Is it considered good or bad practice to use plain JavaScript objects in an AngularJS application?

Imagine needing a custom object that doesn't rely on AngularJS (such as a specific collection with unique functionalities). You could create it independently of AngularJS and simply use it in services/controllers. Alternatively, you could design it a ...

Is npm bundled with node-gyp?

I am currently experiencing an issue where running npm install locally does not produce much output when using npm v6.14.9. However, when I deploy to the server, it generates some incomprehensible messages like: gyp info spawn args ['some properties a ...

Implementing position sticky on a div depending on its content text - step by step guide

If the text inside the .newsDate matches the previous or next .newsDate, I want to make its position sticky when scrolling, until it reaches the next .newsMiddleCont div. What I'm trying to achieve: The same date on multiple news items should s ...

When extracting text using .text(), remember to include spaces between td elements

Is there a method to include space between td's when using .text()? I have searched extensively on Google but could only find information on how to trim space. The code I am currently using is as follows: for (var i = 0, len = rows.length; i < l ...

What is the best way to reposition the origin of the canvas to the center?

As a beginner in html and JavaScript, I am currently working on a program that involves points and lines in a coordinate system. However, the canvas for html5 has its origin at the upper corner, and I need to create a coordinate system with the origin at ...

Removing an item from a JSON array based on its value using jQuery

This is a section of my JSON array: var videos = $j.parseJSON(' [ { "privacy":"public", "id":"1169341693" }, { "privacy":"private", "id":"803641223" }, { "privacy":"public", "id":"1300612600" }, ...... When I use co ...

Working with JSON data in AngularJS: A guide to loading data onto a scope variable

I am in the process of developing my personal website where I want to be able to update content easily without having to mess with the HTML code. My approach involves loading and updating a JSON file to achieve this, however, I am currently struggling with ...

Editing rows directly within the ng table interface

Hey there, I'm currently working on implementing inline row editing using ng table After clicking the edit icon and changing values, I encounter an error upon clicking the save icon: TypeError: Cannot read property 'untrack' of undefined ...

Transferring data using a JavaScript enhanced form

I'm currently working on a search page that showcases results in a table format. I am looking to enhance the functionality using Javascript. The table is contained within a form, and each row offers multiple actions, such as adding a comment. While I ...

The hamburger menu functions properly on the homepage but is not working on the individual about page

The burger menu was causing issues initially due to a simple spelling mistake, which I only noticed later. However, the current issue seems more complex. I am now creating separate pages for different sections of my website, such as About Me, Education, et ...

What is the best way to transfer information from a server running Express.js to a client using React.js?

When using Express.js, I have the ability to send an HTML file that includes a React component. app.get('/index', function(req, res) { res.sendFile(path.join(__dirname + '/src/index.html')); }); Suppose I want to send a uniqu ...

Approach for calculating the total of values during an iteration

I am working with the array $scope.otherDetailsData [0] object amount: 29.9 code: "012" currency: "BRL" payedDate: "2016-11-10" roDate: "2016-08-01" type:"OTHER" [1] object amount: 39.9 code: "013" currency: "BRL" payedDate: "2016-11-11" roDate: "2016- ...

Adjusting or cropping strokes in a JavaScript canvas

I am working with a transparent canvas size 200x200. The object is being drawn line by line on this canvas using the solid stroke method (lineTo()). I'm in need of making this object full-width either before or after ctx.stroke();. https://i.sstatic. ...

Assign a class to a DIV element depending on the ID of an object using Angular

I'm trying to dynamically add a class to a div based on the id of a field in an object. However, my code doesn't seem to be working as expected. Can someone help me debug this? <ng-container *ngFor="let item of cards"> <d ...

Having difficulty setting a value for a tooltip with replaceWith() function

When using jQuery's .replaceWith() method to insert new DOM contents, I noticed that all content gets replaced except for the value of the title. Even though I tried different approaches, the tooltip only displays {{descriptions.title}} instead of the ...

conceal menu upon click (gradually disappear)

This is a basic HTML/CSS menu. Currently, it is functioning properly for page redirection (href). However, I would like it to hide after being clicked on. I plan to call a function that will initiate an AJAX request upon clicking. Here is the code on JS ...

What could be causing the redirection issue in a next.js application?

I recently started working with Next.js and have developed an application using it. On the homepage, I have a timer set for 10 seconds. When the timer hits 0, I want to redirect the user to a feedback page in my "pages" folder. Below is the code I am usin ...