Using ThreeJS to calculate the rotation needed for one Vector3 to align with another Vector3

Recently delving into the world of ThreeJS, I've been exploring its potential for fun and creativity. My current project involves using ThreeJS in conjunction with aframe. The task at hand requires computing with ThreeJS to pass position and rotation data to the aframe component. Despite scouring through various resources, most of them are based on C++ and don't seem to utilize quaternions or ThreeJS.

At the moment, I have a camera positioned at 0,0,0 that I want to rotate towards a specific point in space. Eventually, the system will handle multiple points that can be saved, edited, and selected by users. It seems like storing this information in a matrix array would be ideal. When a point is selected, I need the camera to rotate and face in that direction. The user should be able to switch between points, altering the camera rotation accordingly.

// Seeking to determine the rotation from the camera to a raycast result
const camera = new Vector3()
const cast = new Vector3(10, 0, -20)

// Generating a quaternion based on the vectors to establish the rotation from camera to cast
const quaternion = new Quaternion().setFromUnitVectors(camera, cast)
console.info('quaternion', quaternion.toArray())
// The output is consistently [-0, 0, 0, 1], regardless of the cast's x, y, z values

// Using the quaternion to construct a new Matrix4
const matrix = new Matrix4().makeRotationFromQuaternion(quaternion)
// The output remains constant
// Understandable since the quaternion remains unchanged
console.log(matrix.toArray())

const position = matrix.getPosition() // Vector3(0, 0, 0)
// This generates another matrix
// Unsure how to retrieve the rotation
const rotation = new Matrix4().extractRotation(matrix)

Am I approaching this the right way? The quaternion properties for x, y, z, and w don't seem to vary, indicating a potential mistake on my part.

To summarize my queries:

  1. Why does the quaternion exhibit uniformity regardless of the x, y, z values provided?
  2. How can I ensure the quaternion represents the necessary rotation for the camera?
  3. How do I extract the rotation from a Matrix4?

This journey has been quite challenging, and I fear I might be overlooking something basic.

Thank you,

Jordan

Answer №1

When you want the camera to face a specific point in three.js, you can simply use the function camera.lookAt(point). However, if you need to obtain the rotation without actually rotating the camera, you can achieve this using the following code:

    var matrix = new THREE.Matrix4();
    matrix.lookAt(camera.position, point, camera.up);
    var rotation = new THREE.Euler(0, 0, 0, "XYZ");
    rotation.setFromRotationMatrix(rotation);

Now, the rotation variable will hold the rotation from the camera to the target point. Since the rotation type is THREE.Euler, you can set the rotation using

THREE.Euler.setFromRotationMatrix()
.

Although I am not very familiar with quaternions, they are actually implemented with the matrix4 in three.js. It seems that matrix4 can perform all the functions of quaternions in this context.

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

I'm having trouble with the calculator, unable to identify the issue (Typescript)

I'm struggling with programming a calculator for my class. I followed the instructions from our lesson, but it's not functioning properly and I can't pinpoint the issue. I just need a hint on where the problem might be located. The calculat ...

Express: utilizing rawBody or buffer for a specific endpoint

I am looking to access the rawBody (buffer) specifically for a POST request on one route within my application. Currently, I have the following code snippet in my app.js: app.use(bodyParser.json({ verify: function(req, res, buf) { req.rawBody = buf; }})) ...

Manipulating HTML content with Javascript Array

Is there a way to retain Javascript context from an array? Any suggestions for improving this code? SAMPLE: <html> <script type="text/javascript"> var rand = Math.floor(Math.random() * 6) + 1; var i = Math.floor(Math.random() * 6) + 1; var ...

Error: Conditional formatting not compatible with JavaScript detected

I have a jQuery DataTable that is populated with data from a JSON file. Everything works smoothly, but I'm encountering an issue with conditional formatting. The script I'm using assigns a 'positive' class to all cells in column 2, even ...

Loading texts with the same color code via ajax will reveal there are differences among them

I am currently designing a webshop with green as the primary color scheme. Everything is functioning perfectly, but I have noticed that the text within an ajax loaded div appears brighter than it should be. The text that loads traditionally is noticeably d ...

Hello there, could you please point out where the error is located in this code?

$(document).ready(function(){ $('#nav-b .navbar-item li a').click(function(){ $('#nav-b .navbar-item li a').removeClass('active'); $(this).addClass('active'); }); }); < ...

Tips for eliminating fade effect during hover in networkD3 chart in R

Currently, I have been exploring the usage examples of networkd3 in r I am curious if there is a way to eliminate the hover effect where everything else fades when hovering over a specific node in the graph. For reference, check out "Interacting with igra ...

jQuery: What's the Difference Between Triggering a Click and Calling a Function?

Imagine having certain actions assigned to a link using .click or .live, and wanting to repeat the same action later without duplicating code. What would be the right approach and why? Option 1: $('#link').click(function(){ //do stuff }); //c ...

Can you explain the functionality of `module.exports = mongoose model` in a NodeJs environment

Coming from a front-end React background, I am familiar with statements like import and exports. However, as I delve into learning Backend (NodeJs) with mongoDB, I find myself curious about the mechanics of import and export in this new environment. I hav ...

Establishing a minimum date based on the date selected in the earlier datepicker

My webpage features two date pickers, one for startdate and the other for enddate. The current setup requires that the second datepicker remains inactive until a change is made to the first one. The datepicker for enddate is initially set with the startin ...

Issue encountered while presenting canvas on HTML due to Firebase information

Even though I believe I'm following the correct steps, I am facing an issue where the graph displaying real-time database values is not showing up. The first image shows my real-time database and a demostration as shown in images 2 and 3. While the da ...

Numerical values are not considered by the JavaScript table filter

I'm having trouble with dynamically filtering the content. It works fine for the first two columns, but not for the third one. Maybe I need some additional JavaScript? Here is the link to my snippet: `https://www.w3schools.com/code/tryit.asp?filen ...

JavaScript - Need to automatically scroll to a different div when scrolling occurs

Currently, my focus is on creating a single-page website where the main content is displayed in large boxes arranged vertically down the page. If you have any suggestions or thoughts on using JavaScript to navigate to each content box more efficiently, I ...

Struggling with slow loading times for Three.JS GLTF models? Discover ways to optimize and speed up the load time

My GLTF model (9mb) is loading slowly in ThreeJS. It takes about 4-5 seconds to load on my PC and around 11 seconds on my iPhone. I'm looking for ways to speed up the rendering times. Surprisingly, examples from the ThreeJS website load faster than my ...

Tips for accessing id from $http.get in angular.js

Hello everyone, I'm new to Angular.js and currently learning it. I need help in retrieving data from the following API URL: . I am unsure how to implement this in my controller.js file. Below is the code I have so far, can someone please guide me on h ...

How can you initiate the wizard sequence again in TelegrafJS?

I've created a handler function for "/start" that leads to the wizard scene. Now, I have a message with an inline_keyboard containing a button labeled "redo". When I click on the "redo" button, I want it to restart the entire scene, basically initiat ...

Dealing with JavaScript errors within an Express application

Consider the following async function export async function fetchData() { const result = await fetchData(); return result[0].id; } In the route, there is router.post( '/some-route', handleAsyncError(async (req: Request, resp: Response, _ ...

Is it necessary to use `top` or `parent` when utilizing local scripts in an iFrame?

Is it possible to eliminate the use of top or parent in iFrame localized scripts, as the title suggests? Upon examining the screenshot below, I encounter a "not defined" error unless I include top or parent as a prefix to my function call. test(); does n ...

Generate a configuration file that allows for the reading and storage of modifications

Is there a way to create a configuration file (JSON) on the local file system using JavaScript where I can write and modify data without losing it when the application is restarted? Any suggestions or solutions for this problem? Thank you for your assista ...

Error: Unable to access attributes of null object (specifically 'accessToken')

After following a YouTube tutorial by Lama for creating an E-commerce application, I attempted to add a logout feature on the admin page that was not covered in the tutorial. To implement this, I used Redux to grab the currentUser and set it to null to suc ...