Spin a vector using a perpendicular in Three.js

I need help with vector rotation in Three.js

{x: 0, y: 0, z: 1}

I also have a normal vector:

{x: 1, y: 0, z: 0}

How can I rotate the first vector based on the direction of the normal to achieve this result?

{x: 1, y: 0, z: 0}

Your assistance in this matter will be greatly appreciated. Thank you!

Answer №1

Upon further investigation of this query, I was able to devise a solution that appears to be effective. Visit here for more information

rotateVectorWithNormal(toRotate: Vector3, normal: Vector3) {

    const newVector: Vector3 = new Vector3().copy(toRotate);

    // Establish direction
    let up = new Vector3(0, 1, 0);
    let axis: Vector3;
    // Ensure vector aligns with face normal direction
    // Determine rotation axis
    // Special case when vec == +up or -up because cross will not work
    if (normal.y == 1 || normal.y == -1) {
        axis = new Vector3(1, 0, 0);
    } else {
        axis = new Vector3().cross(up, normal);
    }

    // Calculate amount of rotation
    let radians = Math.acos(normal.dot(up));
    const quat = new Quaternion().setFromAxisAngle(axis, radians);
    newVector.applyQuaternion(quat);

    return newVector;

}

This code is written in Typescript.

Answer №2

Although the automatic answer is accurate, there are some key points to consider about rotations:

When only two vectors, a and b, are provided, there are countless rotations that can transform a into b. The aforementioned solution selects the shortest rotation method but necessitates determining the rotational axis using a cross product. Another approach involves using the bisector as the axis of rotation and rotating by Pi. In this scenario, normalizing to a_n and b_n and rotating around (a_n + b_n) could be an alternative.

The variations in rotations typically impact objects that lack rotational symmetry.

If all vectors are already normalized, the process should be straightforward:

var a = new THREE.Vector3( 0, 0, 1 );
var b = new THREE.Vector3( 1, 0, 0 );
var c = new THREE.Vector3( x, y, z );
var quaternion = new THREE.Quaternion();
quaternion.setFromAxisAngle( a + b, Math.PI );
c.applyQuaternion( quaternion );

If c==a, then c has been rotated onto b; conversely, if c==b, it means c has been rotated onto a.

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

When you duplicate the React State object and make changes to the copied object, it directly affects

When attempting to duplicate a state object, I noticed that the state object is being modified directly in the code snippet below: @boundMethod private _onClickDeleteAttachment(attachmentName: string): void { console.log("_onClickDeleteAttachment | th ...

Do we need to wait a considerable amount of time for an asynchronous function to run in a request?

I have a specific request that I need to address. The first snippet of code shows a function called handleUpdate1 which uses async/await to run a function named _asyncFuncWillRun10Minutes, causing the client to wait approximately 10 minutes for a response ...

Is sending a stream to a variable the best option, or could there be another solution

Is there a way to pipe stream data to a variable? The writable stream examples mentioned in this documentation include: HTTP requests on the client side HTTP responses on the server side Zlib streams Crypto streams TCP sockets Child process stdin Process ...

Updating the default value of a MUI TextField: Step-by-step guide

I am in the final stages of completing my form, but I have encountered an issue when trying to display the current user's name in the defaultValue variable of the TextField from MUI. If the value starts as ""/null, or essentially empty, the ...

The continuous looping issue is being triggered when implementing a like button using firestore along with useEffect and UseState

I have developed a component to be loaded into various cards for displaying data. This particular component retrieves and stores data from the card (sale_id) onto the database. import { LikeButtonStyle } from './LikeButton.styled'; import { Image ...

Autocomplete suggestions from the React Google Maps API are hiding behind the Dialog box

I am currently utilizing the Autocomplete component provided by the @react-google-maps/api package. You can find the documentation for the Autocomplete component here. In the first scenario: In the screenshot below, you can observe that the Autocomplete ...

A comprehensive guide on associating a JavaScript function with an element attribute

I am looking for a way to assign a JavaScript function to an HTML attribute. For example: <li data-ng-repeat="job in jobList" class= dynamicClass(str) data-filter = "dynamicFilter(str)"> The reason I want to do this is because the class name and ...

Executing a function within a worker thread in Node.js

This is the worker I am using: const Worker = require('worker_threads'); const worker = new Worker("function hello () { console.log('hello world');}", { eval: true }) worker.hello() // this is incorrect I want to invoke the hello() fu ...

Changing the names of object keys in JavaScript by utilizing a conversion object

Let's dive right in: I have a list of countries along with their respective values: { Mainland China: 14375, Japan: 20, Thailand: 19, Singapore: 18, South Korea: 15, Hong Kong: 14, Taiwan: 10, Germany: 8, Malaysia: 8, Macau: 7, France: 6, Vietnam: 6 ...

Each time the state changes, the array of components is reset

I'm working on a form to create training programs that display a week, starting with an array of all the days. The rendered day depends on the current day (state). The issue is that every time I switch the current day, such as clicking on a different ...

Designing a Custom Wordpress Extension and Integrating External Scripts

As I dive into the world of WordPress plugin development, I'm seeking guidance from the codex to enhance my skills. Currently, I have a basic plugin that loads a javascript file from a CDN and is supposed to display tooltips. However, I'm facing ...

Steps for dynamically changing the class of a dropdown when an option is selected:

Check out this code snippet : <select class="dd-select" name="UM_Status_Engraving" id="UM_Status_Engraving" onchange="colourFunction(this)"> <option class="dd-select" value="SELECT">SELECT</option> <option class="dd-ok" value= ...

How can one retrieve data from two distinct API routes within a Next.js application?

Currently, I am working with Next.js and facing a challenge in fetching data from two different API routes simultaneously. My intention is to retrieve this data within the getServerSideProps function. The first dataset that I require can be found at the e ...

Hovering over a Raphael animation - What's preventing it from functioning?

I'm currently working on a pie chart using Raphael, and I want to add a tooltip that displays text when hovering over a specific segment of the chart. The hover event is functioning correctly, but I'm having trouble adjusting the tooltip text coo ...

ReactJS state refuses to update

In my FreeCodeCamp leaderboard table, I have implemented functionality where clicking on the highlighted table header calls different URLs based on sorting criteria. The application either calls https://fcctop100.herokuapp.com/api/fccusers/top/recent or ht ...

Error: SyntaxError - Unexpected token 'if' found. Additionally, ReferenceError - berechnung is not defined

I keep encountering two error messages and I'm not sure where the issue lies: Uncaught SyntaxError: Unexpected token 'if' Uncaught ReferenceError: berechnung is not defined Any idea what might be causing this problem? I've reviewed t ...

Looking to connect a dropdown to an icon that has the type "button"?

I am facing a challenge with an icon placed on a Twitter Bootstrap container. My goal is to click on this icon and have a dropdown menu appear, offering various options that link to different websites. Currently, I am able to display the dropdown menu, but ...

What is the significance of the abbreviation 'dbo' in a MongoDB - Express application?

Below is the code snippet provided: app.js const express = require("express"); const app = express(); const cors = require("cors"); require("dotenv").config({ path: "./config.env" }); const port = process.env.PORT | ...

Having trouble parsing JSON elements separately

I am currently working on generating data to be utilized in a chart.js plot by utilizing C# Controller and javascript. The Controller method I have returns a JSONResult to a javascript function. public JsonResult GetPlansPerDoc(){ //Code to retrieve d ...

The ReferenceArrayInput request is lacking an api-prefix

I have been attempting to utilize the ReferenceArrayInput component from react-admin in order to modify a OneToMany relationship. Although the options for the multi-select input load correctly, the actual selection does not work as expected. Interesting ...