Transforming mesh velocity into mesh rotation with Three.js

If I have a three.js mesh along with a velocity vector3.

Elsewhere, the velocity is modified and then added to the mesh.position every frame.

My goal is to have the mesh.rotation aligned with the velocity, making the mesh act like an arrow always pointing in the direction it's moving.

I've attempted two methods, both causing the mesh to rotate inaccurately and in reverse.

//attempt 1
mesh.rot.x = Math.atan2( vel.y, vel.z );
mesh.rot.y = -Math.atan2( vel.x, vel.z );
mesh.rot.z = Math.atan2( vel.x, vel.y );

//attempt 2 inspired from a related stackoverflow post; also unsuccessful
mesh.rot.y = Math.asin( vel.z );
mesh.rot.z = Math.atan2( vel.y, vel.x );

var bankVec = new Vector3( -vel.y, vel.x, 0 );
var upVec = new Vector3( dot( bankVec, vel ) );

mesh.rot.x = Math.atan2(dot(bankVec, vel) / dot(upVec, vel),abs(bankVec)*abs(upVec));

Vector math is quite confusing to me.

Currently, I am randomly changing signs and parameters, hoping for a solution. Any guidance on the appropriate use of dot products, cross products, atan2's would be greatly welcomed.

Not seeking code, just understanding the relevant equations involving dot products, cross products, atan2's, etc.

Answer №1

To create a rotation matrix based on the normalized velocity vector, start by establishing the vector as 1 axis. Then, select a second axis through a specific process. Utilize a cross product calculation to determine the third axis. Finally, perform another cross product operation between the first and third axes to derive the final second axis.

Next, form a 3x3 matrix utilizing the three vectors (the order may vary, such as [x1, y1, z1, x2, y2, z2, x3, y3, z3]).

Alternatively, consider using the Quaternion class:

.setFromUnitVectors ( vFrom, vTo )

This function sets the quaternion to represent the rotation needed to turn direction vector vFrom into direction vector vTo. This method is inspired by . Both vFrom and vTo are assumed to be normalized.

Given that three.js internally favors quaternions, this approach is recommended. For instance, if the arrow points upward, you may set vFrom=[0,1,0] and vTo=velocityVector.normalize();

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

What is the best way to access the child component in React?

const navArr = [ { path: "/introduction", title: "회사소개", subTitle: [{ title: "summary" }, { title: "vision" }], }, ] {navArr.map((obj) => { return ( <NavItem> ...

Revalidation of paths in NextJS 13 is functioning properly for newly created comments, however, it is not working as

I'm encountering an issue with the implementation of revalidatePath() in my CommentForm and PostForm components. Despite both components having a similar structure and functionality, only the CommentForm component is able to utilize revalidatePath() c ...

Utilizing an EJS variable within a React render function with webpack - A Guide

I am looking for a way to display personalized information stored in a MySQL database to my users. I am using ejs, webpack, and React for my project. While I found some guidance on how to achieve this without webpack, it doesn't quite fit my needs. Th ...

Conceal items by clicking using raycasting technology

I'm trying to hide scene objects by clicking on them, but after following multiple tutorials on "raycaster", I'm having trouble identifying where the issue lies. When I open my HTML file, all the objects are hidden, even though I've removed ...

Revolutionizing messaging with Vue JS and Firebase

My web application is designed to check if a user has messages in the Firebase database. If messages are found, it retrieves the data from the users who sent those messages from my local database and displays them in a list using a v-for loop. The display ...

Obtain the inner HTML of a component and store it as a variable in Vue.js 2

Imagine I have a vuejs component named child-component that is inserted into a parent component in the following manner. <child-component> <div>Hello</div> </child-component> Please note, this does not represent the template of ...

Invoking a function from a separate JavaScript file and finding out that an object is considered null

The source code for a word game is stored in Main.js file. Currently, I am attempting to introduce another file called Bookmarks.js (included on the web page prior to the Main.js file). This new file will contain an object var bookmarks = {}; that stays s ...

Which Express.js template allows direct usage of raw HTML code?

I am in search of a template that utilizes pure HTML without any alterations to the language, similar to Jade but keeping the HTML as is. The reason behind this inquiry is: I prefer the simplicity and clarity of HTML I would like to be able to easily vi ...

Javascript Encapsulation example

Could someone help me with this function query: var MyObject3 = function (a, b) { var obj = { myA : a, myB : b } ; obj.foo = function () { return obj.myA + obj.myB ; } ; obj.bar = function (c) { return obj.myA + c ; } ; return obj ; } ; I und ...

What is the best way to send $(this) to a function?

Here is my code snippet: $(document).ready(function(){ var hCount = 0, eCount = 0, nCount = 0, mCount = 0; $("#head").click(function() { var pPos = calculatePosition(hCount); $(this).animate({left:pPos+"px"}, ...

Rotating a rectangular parallelepiped in THREE.js based on the "normal" vectors of two specific faces

Imagine a rectangular parallelepiped in a 3D space positioned on the axis origin with a specific orientation. The largest face, depicted in green, is on the XY plane, while the smallest face, shown in blue, is parallel to the YZ plane. If we have two orth ...

What are the methods to transmit various data formats in an AJAX POST request?

I am facing an issue with sending a JSON object along with two file upload objects to the controller in JavaScript. I have tried the following code snippet: data: {"jsonString":jsonString, "fd":"fd", "fd1":"fd1"}, Is there any other way to achieve this, ...

In JQuery, an empty string will be returned if it contains the dollar sign character

In the scenario presented here, the value is retrieved accurately with the exception of when it includes a $ symbol at the beginning (e.g. $25.00), in which case it consistently results in an empty string. HTML: <input type="number" class="form-contro ...

Leveraging redux within your NEXT.JS project

While working on my Next.js application, I have integrated Redux and Redux Saga. I am trying to incorporate server-side rendering for making HTTP requests: export const getStaticProps = wrapper.getStaticProps(async ({ store }) => { store.dispatch(g ...

Understanding the functionality of imports within modules imported into Angular

I have been scouring through the documentation trying to understand the functionality of the import statement in JavaScript, specifically within the Angular framework. While I grasp the basic concept that it imports modules from other files containing expo ...

Custom headers in XmlHttpRequest: Access control check failed for preflight response

Encountering an issue with an ajax GET Request on REST Server. Test results and details provided below. There are two methods in the REST Server: 1) resource_new_get (returns json data without custom header) 2) resource_api_new_get (also returns json d ...

What is causing the #reset button to trigger the Flow.reset() function when the #gameboard does not contain any child elements?

Whenever I click on the resetBtn, it triggers the Flow.reset function regardless of whether the gameboard has child elements. Am I using the hasChildNodes() method incorrectly? const resetBtn = document.querySelector('#reset'); resetBtn.addEventL ...

Unable to retrieve PHP data using AJAX

Index.html → <form> <div class="form-group"> <!-- <input type="text" id="name" class="form-control" placeholder="Enter Name"> --> </div> <div ...

jQuery's load method is not responsive when prompted via load

I recently came across a unique voting system on that caught my eye. The code they used is as follows: $(".vote").click(function() { $(this).load($(this).attr('href')); console.log("voted"); return false; }); accompanied by this H ...

Utilizing Regular Expressions in AngularJS to validate name, a 10-digit mobile number, and a 12-digit number through the ng-blur event and match

I am struggling to validate the three inputs mentioned above and having trouble using the right functions. Can someone please assist me with this? Here is the HTML code for the 3 inputs: <input id="name" ng-model="user.name" ng-blur="checkIfNameIsVali ...