Determine the global upward direction of an object along any given axis in ThreeJS

I'm struggling to determine the exact rotation of my object around any given axis.

Thus far, I've managed to find the relative rotation of my object using a specific method. To achieve this, I positioned a plane behind the object aligned with the chosen axis. By casting rays on this plane, I am able to gather 3D coordinates which allow me to calculate the angle by employing the atan2 function.

The following code snippet is what I use to obtain the relative rotation of my object:

let planeCrossObjectDir = planeNormal.clone().cross(this.objectUpDirection).normalize();
let projectedPoint = new THREE.Vector3();
rayPlane.projectPoint(intersection.point, projectedPoint);
let centerProjected = new THREE.Vector3();
rayPlane.projectPoint(this.raycastPlane.position, centerProjected);

let u1 = this.objectUpDirection.dot(projectedPoint);
let v1 = planeCrossObjectDir.dot(projectedPoint);
let u2 =  this.objectUpDirection.dot(centerProjected);
let dotv2 = planeCrossObjectDir.dot(centerProjected);

let uvCoord = new THREE.Vector2(u1, v1).sub(new THREE.Vector2(u2, dotv2));

var theta = Math.atan2(uvCoord.y, uvCoord.x); // range [-PI, PI]
theta *= 180 / Math.PI; // range [-180, 180]
if (theta < 0) theta = 360 + theta; // range [0, 360]
let objectsRotation = Math.round(360 - theta); // invert rotation

I aim to extend the same concept to compute the absolute rotation by adjusting the planeCrossObjectDir and making use of the world UP-vector of the plane instead of this.objectUpDirection.

However, the challenge lies in figuring out how exactly to perform this calculation...

To simplify matters and for clearer understanding, I have created a diagram: https://i.sstatic.net/QdqaV.jpg

Answer №1

In my opinion, there may be a more direct route to achieve your goal. The matrixWorld property of your object should already contain all the necessary world values such as position, rotation, and scale. Extracting the rotation component can be done in two ways:

Option 1: Using a matrix

var rotationMatrix = new THREE.Matrix4().extractRotation(yourObject.matrixWorld);
// rotationMatrix now holds the rotation information from your object's world matrix

Option 2: Using a Quaternion

var position = new THREE.Vector3();
var quaternion = new THREE.Quaternion();
var scale = new THREE.Vector3();
yourObject.matrixWorld.decompose(position, quaternion, scale);
// quaternion now represents the world rotation of your object as a quaternion

Applying to the up-vector:

You can then update the up-vector based on the method you chose:

var up1 = new THREE.Vector3(0, 1, 0).applyMatrix4(rotationMatrix).normalize();

Or

var up2 = new THREE.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();

If you explore both approaches, you'll find that they yield similar outcomes (keeping JavaScript limitations in mind).

Feel free to ask any questions or provide clarification if needed.

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

Having difficulties fetching data from Express server to React

My current project involves fetching data from an Express server to a React application using the Fetch API. The Express server interacts with a PostgreSQL database to retrieve relevant data that should be sent to the React frontend. The code snippets bel ...

"Unraveling the Mystery: In Javascript Vue, what is the secret behind the origin of the variable 'e' found in the function

Where does the mysterious variable e in onFileChange(e) come from? In the code snippet below, we see a variable e being used in onFileChange(e). However, this variable is not declared or imported anywhere in the code. How is it possible for this to be val ...

An error occurred: an unexpected identifier was found when trying to import axios using './lib/axios.js' and require('axios')

I am currently working with a js file: test.js: const axios = require('axios'); console.log('test'); To set up the dependencies, I ran the command npm install This is how my folder structure is organized: test node_modules packa ...

Save Scope in JSON format

Currently, I am developing a web application that dynamically displays specific prompts based on the field in focus. There are several different texts stored as scripts that I want to showcase at these different points. My goal is to incorporate scope dat ...

Ensuring the input field and button are positioned in a horizontal line

Currently, I am developing a to-do list application using React and Chakra UI. I am trying to align the input field and the button on the same line for a more organized layout. This is the current layout: image I aim to achieve a design similar to this: ...

Is there a way to show the Username across multiple login pages without using PHP?

Is there a way to dynamically display the username on the Homepage by extracting it from the URL? <div id="login"> <form method="post" action=""> <h2>Login</h2> <p> <label for="username"&g ...

Incorporating an HTML page into a tab through Ajax with the help of a for loop, utilizing Bootstrap 3

Currently, I am developing an Address Book application where the main page displays a series of tabs with the names of the contacts from the contact.objects using a for loop in the code below. How can I utilize ajax to load the information of each contact ...

interaction between modernizr and ajax causing loading issues

I am currently utilizing modernizr.js and a customized ajax function on my page to refresh the content every x seconds. Below is the snippet of code for the functions being triggered. function reloadSlides() { jQuery.ajax({ url: document.locat ...

Dynamically setting the height of elements using jQuery with incremental values

My Objective: I am trying to dynamically adjust the height of each li element within a ul.container. The goal is to find the tallest li, add 25px to its height, and then apply that new height to all other li elements in the container. This calculation ne ...

What is the best method to loop through this object with JavaScript?

Suppose I have the following data: let testData = { 'numGroup1': [[(1, 2, 3, 4, 5), (5, 6, 7, 8, 9)]], 'numGroup2': [[(10, 11, 12, 13, 14), (15, 16, 17, 18, 19)]] }; What is the best approach to iterate through this data using Jav ...

Solving the jQuery Context Menu Issue

I created this JQuery script to dynamically modify links generated on my Page (using Ruby on Rails will_paginate) into GET requests that fetch JSON data and update elements on my page. It works perfectly when the links are left-clicked. However, if a right ...

Challenge with the Nested List Weight Sum algorithm

Trying to crack the challenge "Nested List Weight Sum": Challenge: If given the list [[1,1],2,[1,1]], the expected output is 10. (four 1's at depth 2, one 2 at depth 1) Here's my approach. function calculateDepthSum(nestedList, sum=0, dept ...

There was an error in parsing the JSON syntax while loading models using Three.js GLTFLoader

Discovering how to use Three.js has been an exciting journey for me, thanks to the tutorial available on discoverthreejs.com. Creating meshes and geometry through three.js is a breeze for me. However, things take a turn when I try to import models from B ...

Getting the Angular component class reference within a triggered Highcharts selection event callback - what's the best approach?

It seems like I'm facing a common javascript closure issue, but let me illustrate it with a specific example as I'm struggling to grasp it in an Angular context. In my Angular component, I'm using the Highcharts library to visualize data. W ...

Clicking on the LI element will automatically trigger a click event on the input radio button

Whenever I click on an li element, I want the corresponding radio input to be selected. However, when I try to do this, I'm seeing an error in the console log: Uncaught RangeError: Maximum call stack size exceeded How can I resolve this issue? Bel ...

Increasing the values of id attributes in AngularJS

Here is an example of some HTML code: <tr ng-repeat="x in y"> <td> <div ng-attr-id="{{getId()}}"></div> </td> <td> <div ng-attr-id="{{getId()}}"></div> </td> <t ...

Encountering a Typescript error while attempting to iterate through Enum keys for generating JSX components

I'm really struggling with this problem. Here's a simple enum I have: export enum depositTypes { ACH = 42, Wire = 36, Check = 3, Credit = 2, } I'm trying to create option tags for a select element, like so: Object.keys(depositTyp ...

Sending the object context back to the controller callback from an AngularJS Directive

I am currently working on creating a modified version of ng-change with a delay feature for auto-saving changes. Here is the custom directive I have implemented: myApp.directive('changeDelay', ['$timeout', function ($timeout) { re ...

Highlighted option selection in Material UI dropdown using Cypress

Can someone explain how to select Material-UI dropdown options using Cypress? I'm looking for a simple explanation, thanks! ...

Performing math calculations on data inputted through a form in React Native

As a beginner in React Native, I am working on a simple app that consists of two screens: Calculator and Result. The Calculator screen has two input fields that only accept numeric values. Upon pressing the result button, the app should navigate to the Res ...