Difficulties encountered with camera rotation in Threejs

I have encountered a well-documented issue that has been extensively researched and attempted to resolve. Despite trying various solutions, I am unable to make the final step work successfully. My situation involves a 3D object with an added camera, where I am attempting to establish a first-person setup (camera order set to YXZ). However, when I try to rotate the object on the x-axis, the resulting movement is quite unusual. Surprisingly, the y rotation (left/right) functions correctly. If I initially adjust the x rotation, looking up and down works smoothly as well. Yet, once I turn left or right before attempting to look up/down, the object rotates at a peculiar angle, causing the scene to spiral. Below is a snippet of the code:

                camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);             

                neck = new THREE.Object3D();
                neck.rotateOnAxis(new THREE.Vector3(1, 0, 0), degInRad(90));
                neck.up = new THREE.Vector3(0, 0, 1);
                neck.position.z = 10;
                neck.position.y = -5;
                neck.add(camera);
                scene.add(neck);

                if (leftPressed) {
                        neck.rotation.y += degInRad(1);  //look left
                } else if (rightPressed) {
                    neck.rotation.y -= degInRad(1);      //look right
                }
                if (upPressed) {
                    neck.rotation.x += degInRad(1);      //look up
                } else if (downPressed) {
                    neck.rotation.x -= degInRad(1);      //look down
                }

edit After reading additional questions on GitHub regarding this particular issue, I now understand the challenge associated with rotation order. A more focused version of my question would be: how can I modify the usage of lookAt() (or any alternative method) so that adjusting the x rotation does not impact the y rotation?

Answer №1

Consider creating a separate node (Object3D) for the neck to achieve more control over its rotation. By using two distinct sets of coordinates for rotation, you can rotate the new node along the y-axis and the neck along the x-axis simultaneously. Remember to add the neck to the newly created Object3d node.

.......
var neckNode = new THREE.Object3D();
neckNode.add(neck);
scene.add(neckNode);
.......
if (leftPressed) {
    neckNode.rotation.y += degInRad(1);  //turn left
} else if (rightPressed) {
    neckNode.rotation.y -= degInRad(1);  //turn right
}
if (upPressed) {
    neck.rotation.x += degInRad(1);      //look up
} else if (downPressed) {
    neck.rotation.x -= degInRad(1);      //look down
}

I hope this solution proves helpful.

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

A single list is utilized by multiple HTML5 selects

If I have 10 fields in a form, each requiring a select option from the year 1950 to 2017, can I create one list from that range and have each select reference it? Or do I need to make ten separate lists for each select? Edit: An example could be the birth ...

Is there a way to verify whether the value of a parameter sent to a javascript function is null?

On my hands, lies this piece of javascript code: function modifyButtonState(selectionItem, actionType, pictureCategory) { var $selection = $(selectionItem); var $buttonIcon = $(selectionItem + ' icon'); $buttonIcon.re ...

Error encountered in Intellij for Typescript interface: SyntaxError - Unexpected identifier

I am currently testing a basic interface with the following code: interface TestInterface { id: number; text: string; } const testInterfaceImplementation: TestInterface = { id: 1, text: 'sample text' }; console.log(testInterface ...

Is there a JavaScript method for opening a new window regardless of the PHP file being used?

I have encountered a small dilemma that is causing me frustration. Currently, I have set up a BUTTON on my website. This button, when clicked, triggers a JavaScript function to open a "New Window". The code for this button and function looks like this : ...

When the enter key is pressed, the form will be submitted and the results will be displayed in a modal window without

Behold, my unique form! It lacks the traditional <form></form> tags. <input id="query" name="query" style="font-size: 18pt" id="text" data-email="required" type="text" placeholder="Search Here from <?php echo $row['no']."+"; ?& ...

Troubles arise when trying to convert a schema using Normalizr

Is there a way to efficiently convert a JSON array containing travel expenses into a format that allows for easy retrieval of expenses by travelExpenseId and tripId? [ { "travelExpenseId":11, "tripId":2, "paymentPurpose":"some payment ...

Retrieve a result following an AJAX post request to utilize the obtained value in subsequent code functionalities

Below is the code snippet where an "if" statement is used to check if a query has been executed correctly. If it has, a part of the script is stored in a variable called $output. This variable is then immediately read by the notification script included in ...

Multiply the values of objects by their respective index position

Can someone help me out? I have two different sets of data Data Set 1 29: {value: 29, price: "145"} 30: {value: 30, price: "160"} Data Set 2 29: {value: 29, count: 2} 30: {value: 30, count: 3} I'm attempting to multiply the price by the count at ...

Utilizing Bluebird promises with ES6 object methods

Currently, I am working with node v0.11.14-nightly-20140819-pre on a Windows system where the harmony flag is activated. Within my JavaScript code, there is an object that contains two methods defined in its prototype: function User (args) { this.ser ...

The AnimationMixer is refusing to start playing the animation from the gltf file

I have successfully imported a model using three.js and it works fine. Now, I am trying to run animations from a GLB file. Although I can retrieve the animation names with three.js, the TJS library fails to play my animations. GLB FILE There are two anim ...

After removing the comment from a single line of code, an error is raised: _http_outgoing.js:359 throw new Error('Cannot update headers once they have been sent.');

Upon removing the comment from this line: return done(null, false, { message: 'Incorrect username' }); in the code snippet below, Node.js runs smoothly without any errors. However, if the line remains commented out, Node.js throws an error as men ...

Tips on adjusting a position that shifts with changes in window size

Working on a website for my grandpa, I'm planning to include a small biker character that runs across the screen. When hovered over, he stops and advises "wear a helmet." The animation works well, but there's an issue with the positioning when th ...

Encountering a cannot POST / error while using Express

I am encountering an issue with my RESTful API while using Postman to call the route /websites. Despite my efforts, I keep receiving the error message "Cannot POST /websites". In addition, I am exploring the implementation of a job queue utilizing Express, ...

Error: React Select input control is throwing a TypeError related to event.target

Having trouble changing the state on change using a React Select node module package. It works with regular text input, but I can't quite get it to work with this specific component. The error message "TypeError: event.target is undefined" keeps poppi ...

What is the best way to observe objects in Vue.js?

I have an object containing longitude and latitude coordinates? data(){ return{ center2:{lat:0,lng:0} } } I am attempting to watch these values but it's not working as expected watch:{ "center2.lat":function (newValue, oldValue) { ...

Tips for removing files from an <input type='file' /> element with jQuery or JavaScript

I have multiple <input type='file' /> fields in my file without any HTML form. I need to clear the attached files from a specific <input type='file' />, not all of them. Using $('input').val(""); clears all the < ...

Converting Blob to File in Electron: A step-by-step guide

Is there a way to convert a Blob into a File object in ElectronJS? I attempted the following: return new File([blob], fileName, {lastModified: new Date().getTime(), type: blob.type}); However, it appears that ElectronJs handles the File object differently ...

Oops: Retrieving Information from Request Body in Serverless MongoDB Function

While working with a MongoDB serverless function, I faced a challenge in extracting data from the request body. This led to unexpected errors that needed to be resolved for proper data handling. Upon my attempt to retrieve data from the request body using ...

Implementing a constant loop repeatedly in NextJs

I am seeking assistance with printing the <Icon /> 700 times on a single page. As a newcomer to NextJs, I have successfully used a for loop to console.log the icons but am unsure of how to actually display them. Any help would be greatly appreciated. ...

Displaying checkbox values with JavaScript

How can I display multiple checkbox values when checked in HTML code? Whenever I check a checkbox, I want its value to be shown alongside the previously checked values. Right now, my code only displays one value at a time. Any suggestions on how to achie ...