Determine the scene vector's object-relative local orientation in Three.js based on provided world orientation coordinates

One vector, V, is specified in a particular scene. The vector is defined using World Coordinates (VWx,VWy,VWz), and it is important to note that this is a direction vector, not a position vector.

In the same scene, there is an Object3D with a random orientation (and position).

The goal is to determine the local coordinates (VLx,VLy,VLz) of the direction vector V relative to the Object3D.

An attempt has been made using the following code (derived from WestLangley's response in this thread), but the results are incorrect:


var VW = new THREE.Vector3(10,20,30); 
var VL = new THREE.Vector3(0,0,0); 

givenObject.updateMatrixWorld();

var ob_WorldQuaternion = new THREE.Quaternion(); 
ob_WorldQuaternion  = givenObject.getWorldQuaternion();

var ob_InvWorldQuaternion = new THREE.Quaternion(); 
ob_InvWorldQuaternion = ob_WorldQuaternion.inverse();

VL = VW.applyQuaternion( ob_InvWorldQuaternion);

EDIT(1): It should be noted that the .worldToLocal(vector) method provided by THREE.js for Object3D is not suitable as it is designed for converting position vectors, rather than direction vectors.

EIDT(2): An example application can be seen in this jsfiddle. In this demonstration, the green cone is a child of the green box, and the objective is to keep the green cone pointing in the same world direction as the white world cone.

Answer №1

(Here is an enhanced version of my original response).

Check out this jsfiddle showcasing 3 different methods for aligning child cones.

The red cone maintains a fixed orientation in relation to its parent box.

The green cone is aligned so that its z-axis aligns with the white world cone.

As for the blue cone, its XYZ axes are co-aligned with the XYZ axes of the white world cone.

Here is the code snippet from the initialization function:

cone_geometry = new THREE.CylinderGeometry(3, 40, 120, 40, 10, false);

// The following modification is based on WestLangley's recommendation at:-
// http://stackoverflow.com/questions/13757483/three-js-lookat-seems-to-be-flipped
// When cone.LookAt(PosX) is used, it points the cone Z-axis towards PosX
// (assuming both cone.position and PosX are relative to the same coordinate system).

cone_geometry.applyMatrix(new THREE.Matrix4().makeRotationX(Math.PI / 2));

And here is the core piece of code from the update/animate function:

worldCone.lookAt(target.position); 

var worldVec = new THREE.Vector3();
worldVec.copy(target.position).sub(worldCone.position);

worldBox.rotation.x += 0.01;
worldBox.rotation.y += 0.03;
worldBox.rotation.z += 0.02;

var localVec = new THREE.Vector3();
localVec = F_get_LocalDirectionVector_relativeTo_Object3D_of_WorldDirectionVector(worldBox, worldVec, localVec);

function F_get_LocalDirectionVector_relativeTo_Object3D_of_WorldDirectionVector(givenObject, WDV, LDV) {
    givenObject.updateMatrixWorld(); 

    LDV.copy(WDV)
       .applyQuaternion(givenObject.getWorldQuaternion().inverse());  

    return LDV;
} 

var localCone_G_target_pos = new THREE.Vector3();

localCone_G_target_pos.addVectors(localCone_G.position, localVec);

localCone_R.lookAt(1, 0, 0);
localCone_G.lookAt(localCone_G_target_pos);
localCone_B.lookAt(1, 0, 0);
localCone_B.quaternion.multiply(worldBox.getWorldQuaternion().inverse());
localCone_B.quaternion.multiply(worldCone.quaternion);

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

The OnClick function seems to be unresponsive, however, there are no error messages displaying in

Currently delving into React to enhance my skills, I decided to craft a joke generator. After establishing a local file and successfully fetching the data (jokes) to showcase on the browser, my current goal is to implement a button that, when clicked, will ...

In a production setting, Remix js is experiencing a 403 error when attempting to make a POST request, although it functions properly in a local

While working on my remix.js project, I encountered a 403 forbidden error when making a POST request in the production environment. However, everything works fine in the local environment. Here is the request payload Below are the details of the error, p ...

The Facebook share button on my website is malfunctioning

Could someone please help me figure out why my custom Facebook share button is not functioning properly? When I click the button, the share window fails to appear. I have tested it as an html file on a live web server and have thoroughly reviewed the Faceb ...

The process of flattening an array in Zustand: a comprehensive guide

In my array of brands, each brand object includes a brand name and products. Initially, I successfully added a new brand object to the brands list. However, when attempting to add another brand while keeping the previous brand data intact, it does not fu ...

No error reported upon trying to render json output

I'm having an issue where the following code is not displaying any output. Can someone help me identify what mistake I might be making? This is the HTML file: <head> <script type = "text/javascript"> function ajax_get_json() { var h ...

What is the process to access array elements in AngularJS?

When coding in HTML, <select class="element-margin-top" ng-model="vm.selectedRole" ng-options="(roleName,enabled) in vm.roleNames"> <option value="">All Roles</option>{{vm.roles[0]}} </select> I am tryin ...

Extracting data from a JSON object using Angular

Recently, I've been delving into the world of AngularJS and encountered a hurdle with LocalStorage. After spending numerous hours trying to figure out how to save data locally, I believe I have finally got it working as intended. Now, my next challeng ...

Vue throwing ReferenceError when accessing uninitialized variable in Safari browser

Recently, I've encountered a perplexing error message that has me scratching my head. The error message reads as follows: ReferenceError: Cannot access uninitialized variable. This error specifically points to the line of code: const app = createApp(A ...

Determining the final value of the last handle in a jQuery UI slider with multiple sliders present

I need help retrieving the first and last handle values from a jQuery UI range slider when there are multiple sliders on the page. Currently, my code is set up to grab the last value from the last slider's last handle. I attempted to address this by u ...

The process of setting up React in the terminal becomes tricky when the VS code editor is directing to a non-existent path

Issue with VS Code editor not recognizing existing path Recently attempted to install React using the npx command in the terminal, following steps from various tutorials on YouTube. Despite trying all suggested methods, the installation didn't succee ...

Combining the powers of Express.js, Sequelize, and advanced form validation

As a beginner with Express and Sequelize, I am looking to utilize Sequelize's validation functionality for form submissions without having to duplicate validations on the frontend or rely on additional libraries like express-validator. Below is an exa ...

Enable the execution of a function only once a specific period of time has elapsed

Here's the scenario I'm dealing with: In a fun group chat with my friends, I created a giphy bot that responds to /giphy [terms] messages by posting the top result for those terms. However, my friends started abusing it by spamming the chat. To ...

Is it true that elevating state in React leads to redundant re-rendering?

Currently, I am developing a basic note-taking application using React. Here is a glimpse of the progress made so far: https://i.sstatic.net/nZ1pr.png Each bullet point in the notes corresponds to a 'Cell' component that includes an inner div f ...

Personalizing Google Map pin

I found some code on Codepen to add pointers to a Google map. Currently, it's using default markers but I want to change them to my own. However, I'm not sure where in the code to make this update. Any examples or guidance would be appreciated. ...

Chip input component in React

I've recently upgraded to React 17 and encountered an issue with chip input fields like material-ui-chip-input not working properly. I've tried various npm packages, but none of them seem to be compatible with React version 17. Does anyone know ...

Identifying the class name of SVGAnimatedString

While working on creating an SVG map, I encountered an issue where the functions triggered by hovering over 'g' elements were not functioning as expected. In order to troubleshoot this problem, I decided to check for any issues with the class nam ...

The error "ReferenceError: Component is not defined in Meteor" indicates that the Component

I'm facing an issue while trying to display my Deal component and encountering the error mentioned below. I am currently utilizing Meteor along with ReactJS. Uncaught ReferenceError: Deal is not defined at meteorInstall.imports.routes.routes ...

Unable to access setRowData() in AgGrid/Angular 2 leads to rendering of the grid without displaying any rowData

Resolved I think my solution is temporarily fixed and it reveals that I may have set up my mongoose model incorrectly. The answer provided did assist me in solving my issue, but ultimately the reason for the empty data rows was due to incorrect identifier ...

Creating groups using address strings from a list of users with pre-assigned groupings

In order to extract a list of distinct groups from a list of users, where each user is affiliated with one or more groups at various levels governed by a hierarchy, the hierarchy needs to be reflected in the group as an address similar to an IP address. It ...

Exploring the compatibility between ADFS 2.0 and JSONP

My main website uses passive federation (ADFS 2.0) and includes javascript that communicates with an MVC Web API site using jsonp. I am facing a challenge in getting this WebAPI to support Single Sign On on the same machine but different port. The passive ...