Using three.js lookAt() to align a local axis that is not the positive Z axis towards a different object

Currently, I am in the process of developing an application in which a character (depicted as a cone shape for now) is positioned on a specific surface (currently represented by a cylinder placed horizontally). My goal is to have the character's feet face a designated point (which is currently set as the center of the cylinder).

(Update: I have just realized that the orientation of my Z-axis in the image is incorrect; it should align towards the camera, although the main query remains unchanged.)

Below is a code snippet resembling what I am striving to achieve. https://codepen.io/liamcorbett/pen/YMWayJ (Navigate the cone using arrow keys)

//...

person = CreatePerson();
person.mesh.up = new THREE.Vector3(0, 0, 1);

//
// ...
// 

function updateObj(obj, aboutObj=false){
    let mesh = obj.mesh;
    if (aboutObj) {
        mesh.lookAt(
            aboutObj.mesh.position.x, 
            aboutObj.mesh.position.y, 
            mesh.position.z)
    };
}

//
// ...
//

function animate() {
    // ...

    updateObj(person);

    // ...
}

The provided code somewhat aligns with my objective, however, the problem lies in the fact that lookAt() always directs the local Positive Z-axis in a particular direction, whereas I would prefer it to align with the local Negative Y-axis instead.

I would rather refrain from altering the x, y, z axes of the model itself, as I anticipate complications when implementing additional logic to the character object.

Is it possible to modify the axis used by lookAt()? Or will I need to create a custom lookAt() function? Thank you ~

Answer №1

Is there a way to adjust the axis used by the lookAt() method?

Unfortunately, in three.js, the default local forward vector for 3D objects (excluding cameras) is always (0, 0, 1). Unlike some other engines, three.js does not provide an option to customize the forward vector; only the up vector can be configured. However, this limitation may not be beneficial for your specific situation.

One alternative approach could be to manipulate the geometry itself to achieve a similar outcome.

If modifying the geometry is not an option and you still wish to utilize Object3D.lookAt(), you would need to calculate a different target vector (other than the center of the object).

Answer №2

Although the forward vector of the `lookAt` method may not be adjustable (per Mugen87's comment), it is still possible to alter the local rotation afterwards by understanding the difference between the forward Z axis used and the preferred "upward" axis for your mesh (e.g. a person standing upright on the Y axis).

In your scenario, simply insert this line following the `lookAt` method :

mesh.rotateOnAxis( new THREE.Vector3(1,0,0), Math.PI * -0.5 );

This adjustment will cause the cone to look upward :)

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 update only a portion of a nested schema in mongoose?

UPDATE: Through numerous trials, I finally discovered a successful method that converts any object into a format that mongoose can interpret. Take a look at the solution provided here: const updateNestedObjectParser = (nestedUpdateObject) => { cons ...

Instructions for selecting a checkbox using boolean values

According to the HTML specification, you should use the checked attribute in the <input type="checkbox"> tag to indicate that it is checked. However, I only have a boolean value of either true or false. Unfortunately, I am unable to manipulate the b ...

What sets Vuex apart from a traditional store object?

I'm currently utilizing Vuex for Vue 2 which is similar to Redux for React. Recently, I came across a helpful example that demonstrates updating a counter. Here is the code snippet: import Vuex from 'vuex' import Vue from 'vue' V ...

What are some methods for creating a more affordable sphere in aframe/three js?

In my VR application, I am currently using the aframe <a-sphere> element to render spheres, but it is creating a large number of triangles in my scene, causing a drastic drop in performance with frame rates down to the teens. Is there a more effici ...

Obtaining a file that includes a selection of documents that correspond to a specific search criteria, along with the overall number of

Is it possible to query a collection to retrieve both a limited number of documents matching a query and the total amount of documents that match the query at the same time? This is the desired result: { result : [ { _id:null, ...

Having trouble with Jquery Ajax call in IE8?

I have a dynamic data loading from the database, with each row containing links that perform various actions. Most of them work perfectly fine, but I've noticed an issue with the last one I added – it doesn't seem to be functioning properly on ...

Utilize the client's IP address as a cookie in order to recognize return visits and showcase a special message following the initial visit

First of all, a big thank you to anyone who can help resolve this issue. I apologize if this has been asked before (I couldn't find it anywhere, so I decided to post a new question). The main problem I am facing is getting my webpage to show an alert ...

What is the best way to implement a custom NgbDateParserFormatter from angular-bootstrap in Angular 8?

Currently, I am working on customizing the appearance of dates in a form using Angular-Bootstrap's datepicker with NgbDateParserFormatter. The details can be found at here. My goal is to display the date in the format of year-month-day in the form fi ...

What is a regex with a touch of greed in its capture

I am considering the following options: ' !This is a string! ' '!This is a string !' '! This is a string !' ' ! This is a string! ' ' ! This is a string ' For each of these scenarios, I aim to find ...

Dealing with the validation of two forms on a single webpage: Strategies and Solutions

In a popup, there are two forms that alternate display - one for editing (loaded via ajax) and one for creation. Using jQuery validation, I aim to show hints for both editing and field submission. The validation includes ensuring time spans do not overla ...

Why does the error message "$(…).functionName() is not a function" occur and what steps can be taken to prevent it from

I have encountered a console error message: $(...).functionName() is not a function Here is my function call: $("button").functionName(); This is the actual function: $.fn.functionName = function() { //Do Something }(jQuery); What ca ...

Using node.js to send a response with response.writeHead on the http module

While working on my own custom http module, I stumbled upon a few confusing points while studying the official node.js http module api: When a user utilizes the response.writeHead(statusCode, [reasonPhrase], [headers]) function, are the headers suppose ...

The glb file in Three.js captures the essence of its environment, but lacks the ability to

Using threejs, I've successfully imported and displayed a glb file of a multi-story house with various objects like chairs, tables, and a kitchen. However, I'm struggling to make these objects reflect themselves in addition to the environmental l ...

What is the best way to conceal a ModalPopupExtender that is integrated into an ASCX user control without triggering a postback, utilizing JavaScript?

I am currently working on an Asp.net application and have encountered an issue with the ModalPopupExtender embedded within an ASCX user control. I am trying to set up a cancel button that will hide the popup without triggering a post back when clicked. He ...

Allowing unauthorized cross-origin requests to reach the SailsJS controller despite implementing CORS restrictions

My cors.js file has the following configuration: module.exports.cors = { allRoutes: true, origin: require('./local.js').hosts, // which is 'http://localhost' } I decided to test it by making a request from a random site, Here is ...

Ways to verify if an email has been viewed through the client-side perspective

How can I determine if an email has been read on the client side using PHP? I need to verify if emails sent by me have been opened by recipients on their end. Additionally, I would like to extract the following details from the client's machine: 1. ...

Is it possible to obtain the socket.id of a user immediately upon their connection?

Does anyone know how I can send a personalized message to a user when they connect, without broadcasting it to everyone else? I'd like to use their socket ID with the code io.to(theirSocketID).emit('chat message', 'Welcome');, but ...

Is there a Rails 3 equivalent to $(document).ready() for ensuring that Highcharts loads correctly?

I am facing an issue with my highcharts chart not loading. I am looking for a way to delay the execution of the JavaScript file containing the chart data until after the partial has been passed into building the full page. Can someone provide guidance on ...

Accessing Protected API Endpoint Fails Following Successful Login in Node.js Express API

After developing registration and login APIs with Express, Mongoose, and Node.js, I am currently testing them using Postman. The registration and login functionalities are functioning properly, as the tokens are successfully stored in both cookies and head ...

Developed a hierarchical JSON format using a JavaScript array

I am aiming to generate a properly structured nested JSON file from an array, with unique key values. Currently, I can only output the JSON without any nesting. The desired structure to be displayed in the console is : { "Key" : "data1", "header" ...