Rotating objects in Three.js: Aligning with a target point and orienting towards another location

I'm a beginner when it comes to three.js and 3d programming, so forgive me if this question sounds basic. I'm hoping for an answer that can help me grasp the core concepts.

Currently, I have an object that needs to face another point (in this case, the origin) using the Object3D.lookAt(point) function, which effectively aligns the Z axis of the object towards the point.

However, I also want to rotate my object, named looker, around its Z axis so that its X axis points roughly towards a different object, refObj. I understand that achieving a direct alignment of the X axis with the refObj requires forming a right angle with the origin. My goal is to have the X axis of looker lie on the plane formed by origin, refObj, and looker.

The most apparent way to perform this rotation would be to adjust looker.rotation.z, but I lack the knowledge to calculate the appropriate value.

In essence, I am seeking an enhanced version of the lookAt function that includes a second coordinate for orienting the X axis. Something along these lines:

function lookAtAndOrient(objectToAdjust, pointToLookAt, pointToOrientXTowards)
{
  // Initially look at the pointToLookAt
  objectToAdjust.lookAt(pointToLookAt);

  // Then proceed to rotate the object
  objectToAdjust.rotation.z = ??;
}

I've put together a jsFiddle showcasing the scenario described above

Answer №1

Essentially, what you're requesting is for the y-axis of the object (the object's up-vector) to be perpendicular to the plane.

To achieve this, simply define the object's up-vector before invoking lookAt( origin ).

You can determine the desired up vector by computing the cross-product of two vectors that are confirmed to be within the plane.

Version of three.js used: r.143

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

Connecting NGINX to a Node.js cluster with proxy_pass

After setting up both a NGINX server and a node.js process, the node.js code structure is as follows: function initiateCluster() { var numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for (var i = 0; i ...

Exploring VueJS reactivity: Updating an array with new data

I am struggling to understand why certain methods of changing data seem to work while others do not. In an attempt to clarify, I experimented with the following example: watch: { '$store.state.linedata': function() {this.redraw()} } ...

Tips for generating JSON data in the correct format dynamically while continuously adding new information to the existing object

In my form, users input their email and password, which then generates dynamic JSON upon submission. However, I encountered an issue where the JSON gets corrupted when logging in with different user details as it updates the existing JSON with a new object ...

Combine two arrays in PHP similar to how arrays are pushed together in JavaScript using the `array_merge()` function

I am trying to combine two arrays in PHP: Array1 = [123,456,789]; Array2 = [1,2,3]; The desired combination should look like this: Array3 = [[123,1],[456,2],[789,3]]; In Javascript, I can achieve this using the push() function within a for loop: Arra ...

Unable to transmit form information using HTML/JavaScript/Express Node application

I'm facing a challenge in developing an app that allows me to input event information and then display it on a map. I'm encountering difficulties at the initial stage when it comes to saving the data. Even though Chrome's Inspect tool indica ...

What could be the reason for my inability to reach function attributes?

Struggling with accessing properties in a function that involves callback functions. const example = ( callback: (...args: unknown[]) => unknown ): void => ({ name: callback.name // <- errors // ... }) Encountering issues in typescript d ...

What could be causing an error in a scroll handler when using React's setState function?

Upon reaching the bottom of the page and scrolling back up, an error is thrown by React stating "TypeError: _this.setState is not a function" The scroll handler in question monitors the position of the client on the page. If the client is within the home ...

How can I verify in Javascript that a string contains at least one set of letters and numbers using regex?

I am currently trying to decipher the appropriate regex for identifying a pattern similar to 2d1h30m10s, accepting any valid variation such as 1h, 1h30m, 30m, 10s, or any combination of these. Could regex be the right solution in this scenario? I have bee ...

Using JQuery's .mouseover and .mouseout methods to modify font colors on a webpage

Hi there, I'm new to JQuery and trying to experiment with some basic functionalities. I have a simple navigation menu created using an unordered list, and I want to change the font color of the currently hovered list item using JQuery. However, I&apos ...

Navigating through a JSON file using the map function within a React application

As a newcomer to react, I am currently trying to grasp the concepts involved. Specifically, I am attempting to showcase a collection of email addresses and usernames from a json file structured like this: { "results":[ { "gender":"female" ...

Showcasing the information stored within my li element, I am able to access and view the data through my console

I want to showcase the data in the browser Upon hitting the api call, I retrieve the data in my console. The challenge lies in displaying the data within my li tag. Below are snippets of my relevant code and the entire code can be found in the gist links p ...

Functionality is successful in one browser, yet encounters issues in another

Here is a straightforward script that allows you to choose a State which then determines the Region, and when clicked it directs you to the corresponding website. This script functions perfectly in IE. You can find the code at I've made numerous at ...

When importing the Ionic Native File, the JavaScript File object cannot be used simultaneously

When attempting to use the javascript file object, I encountered an issue because the ionic native file object already uses the same key File Here is an example: import { File } from '@ionic-native/file'; @Component({ selector: 'page-ho ...

Leveraging the useContext and useReducer hooks within NextJS, while encountering the scenario of reading null

Trying to develop a tic-tac-toe game in NextJS and setting up a board context for my components to access. However, after integrating a reducer into the Wrapper to handle a more complex state, I'm encountering a null error. Errors: TypeError: Cannot r ...

I'd really appreciate your assistance in obtaining a value for a specific webelement

I am facing an issue where I am trying to retrieve the value from a WebElement 'input'. The general method getText() doesn't seem to work for me in this case. However, when I tried using JavaScript in the console, it worked perfectly: " ...

"Exploring ways to reattempt a route request upon encountering the $stateNotFound event within AngularUI Router

Managing a large AngularJS application can be quite challenging when it comes to splitting it into functional modules. Currently, all the modules are loaded on the initial page load as they are bundled into a single JavaScript file. However, I am looking t ...

Using LinQ filter along with jQuery tmpl in a jQuery AJAX call illustration

After implementing this script to retrieve and filter a JSON dataset containing 100,000 elements for quick user-side searches, we have encountered performance issues. The script is not running fast enough. Do you have any suggestions on how to optimize th ...

Issue encountered when attempting to pass more than one route parameter in a URL path

My goal is to retrieve data based on the values of 3 fields ("nkk", "nik", and "nama"). In the voters-ctrl: getVotersByParams = async (req, res) => { const nkk = req.params.nkk const nik = req.params.nik const nama = req.params. ...

Mongoose encounters an issue: MissingSchemaError is thrown because the Schema has not been registered for the model

Encountering a perplexing error that I can't seem to resolve. I HAVE NAMED THE REF EXACTLY AS THE MODEL: MissingSchemaError: Schema hasn't been registered for model "ParticipantStatus". Here are the models in question: ParticipantStatus model: c ...

Organize information within a single column of a table according to the heading using Angular

I have been working on implementing a sorting operation in a table for one or multiple columns. Consider the following table: https://i.sstatic.net/F4BJ6.png When clicking on Heading 1, only Data 1 and Data 2 should be sorted. When clicking on Heading 2, ...