Exploring Relative Rotations in Three.js

I currently have a scenario where I have a THREE.Scene containing two meshes, namely meshA and meshB. Both of these meshes have been rotated differently. My objective is to take meshB out of the scene and attach it as a child of meshA, while maintaining its global position and rotation unchanged. Essentially, I want the position and rotation of meshB to remain consistent before and after executing this code.

Here is my nearly successful attempt:

var globalOffset = new THREE.Vector3().subVectors( meshB.position, meshA.position );
var localOffset = meshA.worldToLocal( meshB.position );

var rotationOffset = meshA.quaternion.clone().inverse();
var rotation = meshB.quaternion.clone().multiply( rotationOffset );

scene.remove(meshB);
meshA.add(meshB);

meshB.position = localOffset;
meshB.rotation.setFromQuaternion(rotation);

The positioning aspect functions correctly; however, the rotation only stays accurate if both meshA and meshB have been rotated around the same axis. If they were rotated around different axes, then meshB's rotation seems to alter before and after running this code.

Do you have any suggestions on how I can rectify the above code (or perhaps propose an alternative method) so that meshB retains the same "global" rotation even after being removed and re-added to the scene?

Thank you!

Answer №1

If you're looking to detach meshB from the scene and attach it as a child of meshA, maintaining its global position and rotation, follow these steps:

To accomplish this task, utilize the following code snippet:

meshA.add( meshB );

This solution is applicable for three.js version r.109.

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

How to efficiently remove duplicate items from multiple select dropdowns in Angular using ng-repeat?

Need help with dynamically assigning objects to select boxes in AngularJS. I have a scenario where I add multiple select boxes to a form, but each box should only display items that haven't been selected in other boxes. How can I achieve this functio ...

Utilize Three.js to dynamically rotate objects within a moving Object3D element, ensuring they constantly face the camera

As someone who is relatively new to Threejs, I am curious about how to ensure that a moving mesh always faces the camera in a scene. Within a container Object3D, there are 100 meshes, and I am rotating this container on the x and y axis. Is there a method ...

Obtain the complete path in Vue router by utilizing nested routes

After creating nested routes for Vue Router, I encountered a problem while using the routes to generate a navigation menu. Currently, I am using route.path in 'router-link :to=' which only gives me a part of the path. I want to include the absolu ...

Obtain the current user's Windows username without relying on the ActiveX object

Is there a way to retrieve a client's Windows username in ASP.NET when hosted on a remote server without using an ActiveX object? I tried the following code: Response.Write("HttpContext.Current.Request.LogonUserIdentity.Name " & HttpContext.Cur ...

Guide to making a sliding animation appear when hovering over a menu using jQuery

I have noticed a common feature on many websites, but I am unsure of how to explain it. At times, there are sliding elements in the navigation, like an arrow under menu items that moves when the user hovers over different links. Here is an example of a s ...

Improving the efficiency and readability of JavaScript syntax (specifically conditional statements with if-else) in Vue.js

Seeking advice on optimizing and simplifying this syntax in Vue's methods section: methods: { getColorBtn(status, isCorrect, isRemind, textButton) { if (status === 1 && isCorrect === 1 && isRemind === 1) return 'v-btn--outlined theme--l ...

Sending a Set from a Node.js backend to the front end using socket.io

Why is it that when sending data from a Node.js backend to the frontend using socket.io, a set object is being converted into an empty object? Could this issue be related to JSON limitations, a bug in socket.io, or possibly a bug in Node.js? On the fronte ...

Three.js - Rotation does not follow local orientation accurately

In my current project, I have created an extensive array of objects centered around a focal point within a scene. My goal is to manipulate these objects along their local axes. Initially, I aligned all the objects to face the origin by using a reference ob ...

Removing a cookie in Javascript - step by step guide

Cookie Conundrum: I've encountered a curious scenario involving browser cookies. After entering an invalid login ID, an unauthorized cookie appears on my HTML page. Despite my attempts to display and expire the cookie, it stubbornly remains persistent ...

The Bootstrap navbar stubbornly refuses to hide after being clicked on

Is there a way to adjust the data-offset-top for mobile view? Additionally, I am having trouble hiding the menu when clicking on a link. I have tried some code from stackoverflow without success. Can someone please assist with this issue: <nav class= ...

Sorting columns using custom conditions in DataTables

Within a PHP project I am working on, I have encountered a need to organize a specific column using a custom condition or order rather than relying on the default ordering provided by DataTable (ascending or descending). The project involves four distinct ...

How to Modify the Data in a Dynamic Object within the Vuex Store in a Nuxt Application

Within my Vue/Nuxt project, I have implemented a form where users can add and update dynamic fields for calculating price offers. Upon loading the form, one field is created using the beforeMount lifecycle, with the option for users to add more fields as n ...

The Vue instance methods provide a way to access and manipulate formatted properties

I am looking to implement a method that will generate the appropriate email format to be used as the href value in an anchor tag. This method should return the formatted string in the following format: "mailto:[email protected]". var facultyInformat ...

How can a string be transformed into a JavaScript Object without using JSON?

I have a good grasp on parsing a valid JSON string using JSON.parse('{"key" : "value"}'). But what happens when dealing with a valid JS object, but invalid JSON, such as: JSON.parse("{ key : 'value'}")? The outcome of this example is a ...

employing a variable within a function that is nested within another function

I'm encountering an issue where I am using a variable within a nested function. After assigning a value to it, I pass it to the parent function. However, when I call the function, nothing is displayed. function checkUserExists(identifier) { let user ...

Utilizing NextJS Image Component in Conjunction with Auth0

I have been working on integrating auth0 with nextJS and encountered an issue with the next.js Image component. Let's review the code snippet: import Image from "next/image" import { useUser } from "@auth0/nextjs-auth0" export def ...

The request to http://localhost:5000/error resulted in a 404 (Not Found) error message. I encountered difficulties connecting

When attempting to retrieve information about a product from Amazon using their productId with Express.js and ScraperAPI, an error is encountered: Error message: "{name: "RequestError", message: "Error: Invalid URI "${baseUrl}&url=https://www.amazon.com/d ...

How to Retrieve a Remote File in Angular using $http.get() with OAuth Authentication

I have a unique situation where my users possess private files that require downloads by authenticated users. The server I am using initially downloads a file from S3 utilizing its own set of S3 app_id and secret_token credentials. Once the file has been d ...

Looking to empty a textbox, give it focus, and avoid triggering an ASP.NET postback all with a single click of a

I am working on an ASP.NET project and I have a simple HTML button. When this button is clicked, my goal is to clear textbox1, set the focus on textbox1, and prevent any postback from occurring. However, I am running into an issue where preventing postba ...

Is there a way to determine the quantity of lines within a div using a Vue3 watcher?

Is it feasible to determine the number of text lines in a div without line breaks? I am looking to dynamically display or hide my CTA link based on whether the text is less than or equal to the -webkit-line-clamp value: SCRIPT: const isExpanded = ref(true ...