Stop the model from rotating while using quaternions

Is there a way to rotate a model without it rolling sideways? While using quaternions on a single axis works well, attempting to rotate on multiple axes causes the model to twist.

The original orientation is 0,0,1 https://i.sstatic.net/F79dK.png

Rotating to 1,0,0 works smoothly. https://i.sstatic.net/M5knz.png

However, rotating to 1,1,0 results in undesired rolling/twisting around the original z-axis. https://i.sstatic.net/Z84is.png

Does anyone have suggestions on how to resolve this issue? It seems necessary to constrain the z-axis while applying the quaternion.

Below is the sample code:

//Box's default direction
let vB = new THREE.Vector3(0, 0, 1);

//Cable direction
let vC = new THREE.Vector3(1, 1, 0).normalize();

//Quaternion calculation
let q = new THREE.Quaternion();
q.setFromUnitVectors(vB, vC);

//Box with connector
const boxG = new THREE.BoxGeometry(4, 8, 10);           
const boxM = new THREE.Mesh(boxG, matSS);

const conG = new THREE.CylinderGeometry(0.5, 0.5, 2, 16);
conG.rotateX(Math.PI / 2);
const conM = new THREE.Mesh(conG, matSS);
conM.translateZ(5);
boxM.applyQuaternion(q);            
boxM.add(conM);
scene.add(boxM);

//Connecting cable
const cabG = new THREE.CylinderGeometry(0.25, 0.25, 100, 16);
cabG.rotateX(Math.PI / 2);
const cabM = new THREE.Mesh(cabG, matBL);
const cabP = vC.clone().setLength(50);
cabM.applyQuaternion(q);
cabM.position.set(cabP.x,cabP.y,cabP.z);
   
scene.add(cabM);

I've attempted several approaches such as rotating the Z-axis back, but without success.

Answer №1

The method of locking the z-axis will determine the specific solution needed.

Approach #1: Rotating Polar Angle with Respect to Z-Axis + Azimuthal Angle Rotation in X-Y Plane

If the box's natural direction aligns with the pole, adjusting the box direction can be achieved by specifying another box axis (such as a rotation axis) to modify the roll angle.

// Defining Box's Natural Direction
let vB = new THREE.Vector3(0, 0, 1);

// Setting Cable Direction
let vC = new THREE.Vector3(1, 1, 0).normalize();

// Applying Quaternion Transformation
let q = new THREE.Quaternion();
q.setFromUnitVectors(vB, vC);

console.log("q before", q);

// Determining Box's Rotation Axis 
let vAxisFrom = new THREE.Vector3(0, 1, 0); // or (1, 0, 0)
// Calculating Axis for Quaternion Rotation (from vB to vC)   
let vAxisTo = vB.clone().cross(vC).normalize();

let q_roll = new THREE.Quaternion();
q_roll.setFromUnitVectors(vAxisFrom, vAxisTo);
q.multiply(q_roll);

console.log("q after", q);

Approach #2: Rotating Polar Angle with Respect to Y-Axis + Azimuthal Angle Rotation in Z-X Plane

In this scenario, creating a quaternion by combining a yaw angle rotation around Y-axis and a

pitch angle rotation around X-axis
would provide a straightforward solution.

// Defining Box's Natural Direction
let vB = new THREE.Vector3(0, 0, 1);

// Setting Cable Direction
let vC = new THREE.Vector3(1, 1, 0).normalize();

// Applying Quaternion Transformation
let q = new THREE.Quaternion();
 
let vAxisInPlane = vC.clone().setY(0.0).normalize();
if (vAxisInPlane.lengthSq() < 1.0) {
    q.setFromUnitVectors(vB, vC);
}
else {
    q.setFromUnitVectors(vB, vAxisInPlane);
    console.log("q before", q);
    let q_pitch =  new THREE.Quaternion();
    q_pitch.setFromUnitVectors(vAxisInPlane, vC);
    q.premultiply(q_pitch);
    console.log("q after", q);
}

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

Setting up the path to partials in Node.js using Express, Handlebars, and Consolidate

I am currently developing a Node.js website using Express.js, Handlebars.js, and Consolidate.js. I want to implement partials for common components in my templates but am facing challenges in making them work across different URLs within the site. Within ...

What is the best way to invoke a function within a controller from a .factory service?

I have been working on a code snippet where I am trying to create a generic function. This function, when given the name of a function in my controller, should be run from a factory. app.factory('myfactory', function () { return { cre ...

What is the best way to showcase a collapsible tree using AngularJS and Bootstrap?

I'm currently working on a web application that requires the display of a tree structure using lists. Here is the basic outline: * Node 1 * Node 1.1 * Node 1.1.1 * Node 1.1.1.1 * Node 1.1.2 * Node 1.2 http://jsfid ...

Retrieve the most recent data from mongodb and handle it using a callback function

I'm struggling with adapting the db.collection.find().limit(1).sort({$natural:-1}) query that works in the console to use it in my app. Whenever I try, I encounter a TypeError: Object #<Promise> has no method 'limit' error which leads ...

Struggling to pass command line arguments to index.ts with yarn?

My objective is to pass arguments through the command line using yarn start to index.ts. "scripts": { "start": "tsc-watch --onSuccess \"ts-node --pretty -r tsconfig-paths/register' src/index.ts\"", } When I attempt something like: yarn ...

I'm perplexed by the inner workings of infinite ajax scroll in fetching additional posts

As someone who is new to JavaScript, I find it challenging to grasp the concept, especially when incorporating it with HTML. Despite this, I decided to experiment with infinite ajax scroll functionality. Below is my code snippet: var ias = jQuery.ias({ ...

View Preview Image using the following image tag in JavaScript

I am trying to display an image preview using the img tag that is placed after my input field. Here is my HTML: <input name="image" type="file" id="uploadImage" onchange="PreviewImage(this);" /> ...

Quickest method for skimming through an extremely lengthy document beginning at any specified line X

In my current project, there is a text file that is written to by a python program and read by another program to display on a web browser. JavaScript handles the reading process at the moment, but I am considering moving this functionality to python. The ...

What is the best way to retrieve the UTC value of a specific date and time within a particular time zone using JavaScript?

I want to create a Date object with a specific time: "Midnight in Los Angeles on Christmas 2011". Although I've used moment.js, which is good, and moment-timezone, which is even better, neither the default Date class nor moment constructors allow for ...

Tips for finishing Vuetify's circular progress bar using a center percentage value

I've been exploring the features of Vuetify's progress circular component lately. This component allows you to specify a value prop, which represents the current progress percentage. The circle completes when the value reaches 100. In my scenar ...

Do these two JavaScript statements behave the same under the principles of functional programming in a React environment?

Is there a rule in functional programming that states these two approaches are equivalent? When working on a React application, I initially passed a function as an attribute using the second version where the first parameter is also passed. Out of curiosi ...

The SEMrush API is not displaying an 'Access-Control-Allow-Origin' header on the requested resource

When attempting to utilize the SEMrush API, I made a request using jQuery as shown below: $(document).ready(function() { $.get( 'https://api.semrush.com', { type: 'phrase_this', key: ' ...

What is the process for submitting my jquery modal form?

Having trouble with my simple jquery modal form. I believe there's a small issue, but I can't seem to locate the error. Any help would be appreciated. Here is the form field I'm working on: <form id="dialog-form" action="insertcus.ph ...

Step-by-step guide on replacing the {{content}} placeholder in HTML with text saved in local storage

I am working on a page called showdesign.html, which contains only 4 lines of code: <script> var data = JSON.parse(localStorage.getItem("templateType")); document.write(data.template_code); console.log(data.template_code); $("#main-wrapper").html( ...

Jquery is not working as expected

I am having trouble implementing a jQuery function to show and hide select components. It doesn't seem to be working correctly. Can someone help me identify the issue? <html> <head> <meta charset='UTF-8' /> <script ...

The forceShutdown function in the node.js grpc server does not properly terminate the server

I encountered an issue with restarting a grpc node js server after shutting it down When attempting to restart the grpc server after forceShutdown, I received the following error: Error: Server is already running This snippet shows the problematic code: ...

Can CASL React library be trusted for authorization security?

I recently discovered the CASL JavaScript library, which helps restrict what resources a client can access. I'm curious to know if it's possible to use CASL for role-based access in a React application while ensuring security? Also, I wonder if ...

Creating a Loop with JavaScript through a List

My current API response format is: "imagePath": "path1", Here is the JavaScript code I am using: <div className="flexAlignCenterJustifyCenter"> {event.imagePath ? ( <img src={event.imagePath} onErro ...

Tips for utilizing canvas within Angular applications

When working with canvas in JavaScript, the usual approach is: var canvas = document.getElementById('tutorial'); var ctx = canvas.getContext('2d'); However, when it comes to Angular2, I am unable to access the HTMLCanvasElement object ...

Unsuccessful attempt to send data using AJAX on the API

I'm at a loss here - I've tried everything, and I just can't seem to figure out what the issue is. I'm attempting to make a 'POST' request to my teacher's server for a homework assignment, but for some reason it's no ...