Unexpected issue: THREE js Object position does not update after rotation

For the past couple of weeks, I've been engrossed in creating a solar system model using Three.js. After following tutorials and documentation, I successfully created a working model of the solar system. However, I encountered an issue when trying to zoom in on a specific planet upon clicking it. While the code works fine for the stationary sun, it fails to focus on the clicked planet correctly as it always zooms back to its initial empty position.

To simulate the orbiting or revolution of the planets around the sun, I created invisible parent objects positioned at the sun's location and rotated them accordingly in the animate() function. This approach made the planet revolution work smoothly, but the position of the planets remained unchanged. Even after attempting to use the update matrix function, the issue persists.

I devised a function that takes the initial position of the planet, the distance between the sun/parent object and the planet, the angular speed (rotation speed) of the respective parent object, and the number of times the rotatey function was called in the animate() function. There seems to be an issue with this function or perhaps my overall approach to solving the problem. Any help in rectifying this function or suggesting an alternative way to determine the object's position would be greatly appreciated.

function calculateCurrentPosition(initialPos, distance, angularSpeed, time) {
    console.log(initialPos, distance, angularSpeed, time);
    if (time === 0) {
        return initialPos;
    }
    var currentAngle = angularSpeed * time;
    var currentX = initialPos.x + distance * Math.cos(currentAngle);
    var currentZ = initialPos.z + distance * Math.sin(currentAngle);
    return { x: currentX, y: initialPos.y, z: currentZ };
}

The movement occurs along the x-z plane, therefore the y-coordinate remains constant.

The code snippet used to create the planet object is as follows:

function createPlanete(size, texture, position, ring) {
    const geo = new THREE.SphereGeometry(size, 30, 30);
    const mat = new THREE.MeshStandardMaterial({
        map: textureLoader.load(texture)
    });
    const mesh = new THREE.Mesh(geo, mat);
    const obj = new THREE.Object3D();
    obj.add(mesh);
    if(ring) {
        const ringGeo = new THREE.RingGeometry(
            ring.innerRadius,
            ring.outerRadius,
            32);
        const ringMat = new THREE.MeshBasicMaterial({
            map: textureLoader.load(ring.texture),
            side: THREE.DoubleSide
        });
        const ringMesh = new THREE.Mesh(ringGeo, ringMat);
        obj.add(ringMesh);
        ringMesh.position.x = position;
        ringMesh.rotation.x = -0.5*Math.PI;
    }
    scene.add(obj);
    mesh.position.x = position;
    return {mesh, obj}
}

If you require any additional information regarding the code or have further questions, feel free to ask.

Answer №1

After some investigation, it turns out my approach was incorrect all along. I ended up utilizing

obj.parent.children[0].getWorldPosition(target);
and successfully resolved the issue by obtaining the child's position and storing it in the target variable. In this scenario, obj refers to the selected object (specifically a planet). The parent is responsible for managing the planet's rotation to simulate orbiting behavior.

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

Unit testing React Native for inputting text values

I am attempting to append a unit to the value of a textInput: https://i.sstatic.net/EqswS.jpg I have attempted to achieve this with the following code but have not been successful: value = { this.state.totalWeight + " Kgs"} I also tried adding ...

Why is my call to the node.js server not receiving a response?

While using Chrome or Postman, I encountered an issue when sending a simple get request without any parameters. After waiting for 2 minutes, I received an error message instead of the expected response. My expectation was to receive a "cannot get" message ...

Advantages of utilizing bracket notation (alongside variables) for retrieving a property from an object

When it comes to accessing stored information, utilizing alternatives like the dot operator can be straightforward. However, I’m struggling to grasp the significance of using variables in achieving the same goal. For instance: var myObj = { prop1: "v ...

Refresh gif without having to reload it in Internet Explorer 11

I'm attempting to create a feature where a gif restarts when clicked by the user, without needing to reload it (due to the heavy size of the gif which is preloaded for my application). The current code functions flawlessly on Chrome and other "modern ...

When using @testing-library/react (rtl), the 'waitFor' function achieves success even without the need for the 'await' keyword

waitFor() is causing my test to fail while waitFor() (without await) makes it pass. The official documentation states: Async methods return a Promise, so you must always use await or .then(done) when calling them. (https://testing-library.com/docs/guide ...

Using a Function to Retrieve Styles in React Native for Android

My goal is to dynamically add views based on the data received from JSON. Each event should be represented with a different color: red or blue. The app will insert a view accordingly. class MainPage2 extends Component { constructor () { super() var s ...

Blurred entities aligning in front of one another (THREE.JS)

While experimenting with three.js, I encountered an issue with objects appearing fuzzy when they overlap. The distortion looks like this. Can anyone provide assistance with this problem? Below is the code I'm currently using: // Initializing basic o ...

Does the XMLHttpRequests have a NavigationTiming interface that can be utilized?

While the window.performance object offers insights into the performance of the browser's last page load, such as DNS lookup times, I have not come across a similar feature for Ajax calls. The overarching issue I am aiming to address is the ability t ...

Synchronize display with data loading

My plan involves executing 2 AJAX calls: Loading a partial HTML template. Fetching JSON data for the template and displaying it within the loaded template. The JSON must be retrieved separately from the template because users might initiate a "refresh" ...

To enable the description p tag only when the search box text matches the search criteria, otherwise keep the p tag disabled

I need to develop a search feature that includes a search box, a heading, and a paragraph description. Initially, the description should be hidden, but when a user enters text that matches the description, the paragraph tag should become visible. An exampl ...

What could be causing this axios.get request to fail?

I am currently enrolled in Colt Steele's Web Developer bootcamp and facing a challenge... In the tutorial, we are using axios as 'request' has been discontinued, so I am trying to follow along with this change. My goal is to set up a Get r ...

Issues with retrieving the output of a function nested within another function through an ajax request

I am attempting to use jQuery to add the results of an ajax call to a paragraph. My goal is to extract the "myResult" variable from the inner getResult function and transfer it to the outer buildParagraph function. Unfortunately, the returned value is und ...

The issue of JQuery recursion not properly focusing on a textbox

Can anyone help with a jquery focus issue I'm experiencing? My goal is to address the placeholder problem in IE by focusing on an element and then blurring it to display the placeholder. This functionality is being used in a modal form. Initially, e ...

Retrieve the $http data from a function that is external to it

Apologies if the title is confusing, it's hard to explain in a different way. The situation I have is... app.controller('viewProductController', ['$scope', 'dataFactory', '$routeParams', function($scope, dat ...

The code snippet contained within the Highlight component is rendered in a continuous, unbroken line

The code snippet within the Highlight component is currently displaying as one long single line. Is there a way to include multiple lines of code within the Highlight component? ...

The functionality of linear mode seems to be malfunctioning when using separate components in the mat-horizontal-stepper

In an effort to break down the components of each step in mat-horizontal-stepper, I have included the following HTML code. <mat-horizontal-stepper [linear]="true" #stepper> <mat-step [stepControl]="selectAdvType"> <ng-template matStep ...

Mastering Vue 3: Simplifying a reactive array of objects while maintaining reactivity

Struggling with maintaining reactivity in Vue 3 when flattening a nested array of objects. Unfortunately, my attempts result in crashing and browser hang-ups. In my Vue 3 component, I have an array structured as a list of objects: this.grouped = [ ...

jQuery Load - Oops! There seems to be a syntax error: Unexpected token <

Error: Uncaught SyntaxError: Unexpected token < I encountered the error message mentioned above while trying to execute a jQuery load function: $('#footer').load(UrlOfFooterContent); The variable UrlOfFooterContent holds the URL of an MVC c ...

After inserting the Telerik component, the code <% ... %> is throwing an error

I have a webpage with ASPX that utilizes JavaScript and ASP components without issues. However, after adding a Telerik combobox, I encountered an error: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %& ...

Having trouble getting datatables.net to function properly with JavaScript

I've been experimenting with datatables from http://datatables.net/ Attempting to make it work using javascript, but I'm facing issues. Even when following the example provided on the website, it still shows a blank page. Does anyone have any su ...