spinning in relation to another object

Currently, I am working on developing a simple Three.js application. One of the main objectives is to synchronize the moon's movements with the Earth's. Although I have a method that allows the moon to rotate in a circular motion statically, the rotation pattern gets disrupted when you move around the planet, causing the moon's path to become elliptical until it realigns after a few rotations.

The function responsible for this rotation can be seen below:

rotateMoon = function(rotSpeed) {
  var x = moon.position.x,
      y = moon.position.y,
      z = moon.position.z;
  moon.position.x = x * Math.cos(rotSpeed) + z * Math.sin(rotSpeed);
  moon.position.z = z * Math.cos(rotSpeed) - x * Math.sin(rotSpeed);
}

My objective is to connect the moon's movement to the Earth's, essentially making it dependent on the Earth's rotation. How can I achieve this seamless synchronization?

Answer №1

Consider utilizing THREE.js for this task as it offers simplicity and ease of use.

One way to manage objects is by creating a parent-child relationship, for example, Earth being the parent of Moon.

Check out the sample code snippet below:

var earth = new THREE.Mesh(e_geometry, e_material);
var moon = new THREE.Mesh(m_geometry, m_material);
moon.position.x = 100;
earth.add(moon);

When it comes to updating, you can incorporate the following in the method or function:

earth.rotation.y += 0.01;

The THREE.js website offers a range of examples demonstrating such an approach.

Furthermore, you can explore the concept of a scenegraph, where elements like a car's wheels are positioned relative to the parent car node:

car
|
+--left front wheel
|
+--right front wheel
|
+--left rear wheel
|
+--right rear wheel

In the case of planets, additional nodes can be added to allow for independent rotations of Earth and Moon while the Moon orbits the Earth:

earthBase (invisible)
|
+--earth
|
+--moonBase (invisible)
   |
   +--moon

By utilizing THREE.Object3D() for earthBase and moonBase, you can establish the hierarchy effectively:

earthBase.add(earth);
earthBase.add(moonBase);
moonBase.add(moon);

Adjust the orbit radius and speeds accordingly to achieve the desired animation effects.

Feel free to test out a live example on this fiddle http://jsfiddle.net/greggman/uY8Ce/

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

Update the row striping pattern once an element has been removed

I've been working on creating a todo-list and implemented row striping. Everything was going smoothly until I realized that when I delete a task, the row striping does not update as intended. Instead of changing to white, white, beige after a deletion ...

Ways to retrieve JSON string from responsetext in JavaScript

After spending the entire day on this, I still can't figure it out. I have AJAX that fetches a JSON string from a PHP script, but now I need to work with it in JavaScript. Here's what I've tried: var xmlhttp; xmlhttp=new XMLHttpRequest(); ...

Encountering the "Error: data.map is not a function" issue within Next.js

I'm having trouble understanding why this first fetch call works perfectly: async function getData() { const res = await fetch('https://jsonplaceholder.typicode.com/todos') return res.json() } export default async function Home() { co ...

Implementing a JavaScript function to a button within an existing form in JSP - Best practices

Currently, I am working on developing multiple JSP pages and I encountered a requirement where I needed to add a function to a button within an already existing form. The challenge was that the form's submit button was configured to navigate to anothe ...

Invoke a function that generates an array within a v-for loop and iterate through the elements in a Vue.js component

Seeking guidance on the optimal approach for this task. I need to invoke a method within a v-for loop that lazily loads data from a related model. Can anyone advise on the best practice for achieving this? <div v-for="speaker in allSpeaker" :k ...

Axios Instance class request cancellation

In my Redux-saga project, I am working on implementing a polling function where I need to make a request every second. If there is no response from the endpoint, I want to cancel the previous request and initiate a new one using Axios client. I have organi ...

An elementary React project facing compilation issues

I'm currently exploring react hooks, but I encountered an error with the useReducer hook. The console displays the following error message: "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happe ...

In Internet Explorer 10, it is not possible to access the document.links using the link's id; it can only be accessed using the

Why does the following code work in FireFox 23.0.1 and Chrome 29, but not in IE 10? <!DOCTYPE html> <html> <head> <title></title> <script type="text/javascript"> function loadFile1(){ a ...

Utilizing Jquery to interchange two values and update styling

I am looking to create a script that allows me to select a black div by clicking on it (turning it red), and then transfer the value from the black div into a white div with another click. The functionality works as expected when swapping values between tw ...

Creating a JSFiddle with sprites using source and image files from Github with THREE.JS - a step-by-step guide

Greetings! I am currently working on creating a JSFiddle based on the official THREE.js HUD Sprites example. However, I am facing an issue where the sprite images do not seem to load or apply using the URLs specified in the original file:- //... URL' ...

"Using Node.js to create a simulated mobile environment: a step-by-step guide

I am seeking a way to replicate the functionalities of a mobile browser using Node.js. This means that all mobile browser features should be accessible on the client-side, even if they are simulated. The goal is for webpages to believe they are being load ...

What is the best way to position two elements floated to the right in separate rows within a single row?

Having trouble with a web design issue. I am currently working on a website and trying to format an input field with a label so that the label sits on top of the input while floating to the right. However, I'm encountering difficulties as the elements ...

My WCF service has a JavaScript endpoint that is compatible only with Internet Explorer

My challenge is to access a remote server with a webhttpbinding using JavaScript. Here's a simple JavaScript function that runs the test function, a random number generator that returns a number: Function DoTest() { var xmlHttp = new XMLHttpRequ ...

Declarations and expressions in Node.js using JavaScript

Recently diving into Node Js, I stumbled upon the following code snippet in a tutorial const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); const questions = [ " ...

Guide to displaying a function result in Vue 3

I have just started learning vue js and I am facing an issue. I want to display the value returned by the following function in a table row: The function is: getGroup(id){ this.users.forEach(element =>{ if(element.id===id) ...

Creating an overlay with CSS hover on a separate element and the ::before pseudo class

Issue: I am struggling to display the overlay when hovering over the circle element, rather than just the image itself. I have attempted to achieve this using CSS, but can't seem to make it work as intended. Any guidance and examples using JavaScript ...

Pausing a running function in React

Exploring Visual Sorting Algorithms In the process of creating a visual sorting algorithms tool for educational purposes, I have developed a function called sortArray() that handles the animation of the sorting process on arrays. The functionality is evid ...

What is the best method to send the HTML button ID to a Python file through Django?

I have the following HTML code snippet that generates dynamic buttons: {% for i in loop_times %} <button type="submit" class="'btn btn-lg" name="{{ i }}" id="{{ i }}" onclick="alert(this.id)" formmethod="post"><a href="{% url 'button ...

Tips for ensuring the Google Maps API script has loaded before executing a custom directive on the homepage of an Angular website

Issue - I am facing issues with Google Maps autocomplete drop-down not working on my website's main page even after parsing and loading the Google Maps API script. The problem seems to be a race condition on the main page of my website, specifically i ...

Tips for achieving printing with the "Fit sheet on one page" option in JavaScript

Is there a way to print a large table of data with 200 or 300 rows all on one page, similar to the Online MS Excel print option 'Fit Sheet on One Page'? I attempted the code below: var tble = document.createElement("table"); tble.id = "tble"; d ...