How to extract the rotation of the world from the THREE JS matrixWorld

Is there a way to retrieve the world rotation of an Object3D in three.js? I am aware of how to obtain the world position of an Object3D using object.matrixWorld, but I am unsure about how to acquire the world rotation of an object.

This information is crucial for the following issue I'm facing: I have a hierarchical structure of Objects laid out like this:

var obj1 = new THREE.Object3D();
obj1.x = 200;
obj1.rotation.x = 0.1;
scene.add(obj1);

var obj2 = new THREE.Object3D();
obj2.y = -400;
obj2.rotation.y = 0.21;
obj1.add(obj2);

var obj3 = new THREE.Object3D();
obj3.z = -200;
obj3.rotation.x = 0.1;
obj3.rotation.y = -0.1;
obj2.add(obj3);

My goal is to align my camera orthogonal to obj3 at a specific distance. When no rotations are applied to the objects, the solution looks something like this:

var relativeCameraOffset = new THREE.Vector3(0, 0, 500); // 500 represents the z-distance from my object
var cameraOffset = relativeCameraOffset.applyMatrix4(obj3.matrixWorld);
camera.position = cameraOffset;

If only the last child object is rotated, adding this line achieves the desired outcome:

camera.rotation = obj3.rotation;

However, when all parent elements are rotated, this approach fails. Therefore, I am seeking a method to determine the global "orientation" of my 3D object. Thank you.

Answer №1

To obtain the rotation of the "world," you can follow this method:

const position = new THREE.Vector3(); // initialize and reuse
const quaternion = new THREE.Quaternion();
const scale = new THREE.Vector3();

mesh.matrixWorld.decompose( position, quaternion, scale );

You can then adjust your camera's orientation using the following code:

camera.quaternion.copy( quaternion );

Note: when directly accessing matrixWorld, ensure it is updated. Normally, the renderer handles this in the render loop. But if needed in between renders, manually update the matrix with:

mesh.updateWorldMatrix( true, false );

UPDATE: A new method has been introduced. Refer to the source code for more information.

Object3D.getWorldQuaternion( targetQuaternion );

three.js r.147

Answer №2

To establish a connection between camera and obj3, simply execute the following code:

obj3.add(camera);

Answer №3

To retrieve the world position of an object, employ mesh.getWorldPosition(), and for its rotation, utilize mesh.getWorldRotation().

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

Ensure your TypeScript class includes functionality to throw an error if the constructor parameter is passed as undefined

My class has multiple parameters, and a simplified version is displayed below: class data { ID: string; desp: string; constructor(con_ID:string,con_desp:string){ this.ID = con_ID; this.desp = con_desp; } } When I retrieve ...

Utilize dynamic Google Maps markers in Angular by incorporating HTTP requests

Struggling to find a solution for this issue, but it seems like it should be simple enough. Initially, I fetch my JSON data using the code snippet below: testApp.controller("cat0Controller", function($scope, $http){ var url = "../../../Data/JSONs/randomd ...

404 Response Generated by Express Routes

Exploring the MEAN stack has been a great way for me to expand my knowledge of node and express. Currently, I am working on creating a simple link between two static pages within the app. My routes are set up as follows: //Home route var index = require( ...

Utilize external functions in evaluated code

After working with a TypeScript file containing the following code: import { functionTest } from './function_test' function runnerFunctionTest() { console.log("Test"); } export class Runner { run(source : string) { eva ...

How to access Bootstrap's modal initial data-* upon closing

When displaying a bootstrap modal, a convenient method to retrieve associated data is by using the following code snippet: $('#myModal').on('show.bs.modal', function (e) { var id = $(e.relatedTarget).data('id'); alert( ...

What is the best way to navigate around and close this modal?

Hey everyone, I've been experimenting with the JavaScript on this codepen and I'm trying to make it so that when you click the background, the modal closes. However, I've run into two issues: The .modal is contained within .modal-backgroun ...

Attempting to assign a File object as a property to a component but receiving an empty object in return. I'm curious about the security implications of this as well

I created a modal for previewing avatars with a generic design: <avatar-update :img-file="avatarFile" :show="avatarModalShow" :img-url="url" @close="avatarModalShow = !avatarModalShow" :change-avatar="updateCrop" @destroyUrl="imgUrl = null"> </av ...

Can someone help me troubleshoot why my multi-step form is not functioning properly?

I've been working on a multi-phase form, but it's not behaving as expected. I've tried different code variations, but for some reason, it's not functioning properly. After spending two days on it, I'm starting to feel a bit frustra ...

Has anyone ever tried creating a personalized shirt design similar to what tailorstore offers? I'm in search of some

I am seeking advice on how to create a custom shirt design feature similar to the one on tailorstore.co.in (CUSTOMIZING SHIRT). As I explored further, I speculated that they may have: 1. Developed 3D models and generated numerous combinations. - Th ...

The player clicks once and the game is played two times

Struggling with a coding issue here. I've got some code where you click on an image and if it can be moved to the next cell, it should move. function changecell(a){ var moved=false; if(a%3 !=0) { if(ij[a-1]==0) { moved=true; ...

How do I incorporate an external template in Mustache.js?

Welcome, I am a beginner in using Mustache.js. Below is the template and JS code that I have: var template = $('#pageTpl').html(); var html = Mustache.to_html(template, data); $('#sampleArea').html(html); Here is the template ...

What is the most efficient method for executing over 1,000 queries on MongoDB using nodejs?

I have a task to run around 1,000 queries on MongoDB in order to check for matches on a specific object property. I must confess that my code is quite amateurish, but I am open to any suggestions on how to improve its efficiency. The current version works ...

What is the best way to create a variable in a React component that requires asynchronously loaded data in order to be functional?

While I have a good understanding of passing data from one component to another using this.props, I am encountering difficulty in asynchronously fetching and storing values, such as from a database, that need to be accessed throughout the component. The ch ...

Is `activeClassName` not being recognized by React?

I've been trying to figure out what's wrong with this code, but I can't seem to find a solution anywhere online. Can someone please help me? This code works fine in my other application, so I'm not sure why it's causing issues here ...

Having trouble with AngularJS integration in Node.js Express framework?

My AngularJS HTML file is below, and I am accessing it using http://localhost:3000/modulename/create. However, the issue arises as AngularJS is not functioning properly. For example, the ng-repeat directive is empty in the template, whereas when we console ...

What could be causing my canvas to not display my sprite?

Currently, I am in the process of learning JavaScript and experimenting with creating games to make the learning experience more enjoyable. However, I am facing an issue while using EaselJS and CreateJS to develop these games as a beginner. I need some as ...

Having trouble converting JSON object to regular object?

I'm trying to change a JSON object into a regular object by using this method... var slaobj = eval('('+s+')'); However, it doesn't appear to be working correctly (the `.length' is returning as undefined). What m ...

When using AJAX POST requests, HTML links may become unresponsive

Scenario: Currently, I am developing a small-scale web application. The AJAX functionality is successfully sending data to create.php which then executes the necessary MySQL query. Upon completion of the AJAX request, a success message is appended to the d ...

Discover the initial two instances of a specific element within a collection of javascript objects

Within my javascript arraylist, I am currently storing the following elements: list = [ {header: "header1", code: ""}, {label: "label1", price: 10}, {header: "header2", code: ""}, {header: "header3", code: ""}, {header: "header4", code: ""} ] My que ...

Tips for avoiding page reload when submitting a form with form.submit() in ReactJs

Is there a way to avoid the page from refreshing when triggering form submission programmatically in ReactJS? I have attempted to use this block of code: const myForm = () => <form onBlur={(e) => { if(!e.relatedTa ...