Align the camera to be perpendicular with the ground

Ensuring that my fly camera always remains parallel to the ground is crucial to me. Specifically, I need my camera's right vector to always be (1,0,0).

To achieve this, I have developed a customized Camera Controller in three.js that simulates unique camera movements and pointerlock behavior.

Below is the main rotation code within the update method:

this.tmpQuaternion: THREE.Quaternion;
this.camera: THREE.PerspectiveCamera;
...
this.tmpQuaternion
 .set(
   -this.verticalRotationSpeed * this.mouseMovement.movementY,
   -this.horizontalRotationSpeed * this.mouseMovement.movementX,
   0,
   1
 )
 .normalize();
this.camera.quaternion.multiply(this.tmpQuaternion);

In this code, verticalRotationSpeed and horizontalRotationSpeed are simple positive constants, while mouseMovement.movementX and mouseMovement.movementY represent the accumulated mouse movements since the last frame.

However, I have noticed that when I move my mouse simultaneously along both the X and Y axis, the camera tends to roll slightly along the z axis, which is not desired.

I would appreciate insight into the root cause of this behavior or, if possible, a revised version of the code that maintains the camera's right vector facing (1,0,0) at all times.

Note: I am specifically seeking a solution within the three.js library.

Thank you for your assistance.

Answer №1

Shoutout to WestLangley for helping me solve my issue.

Check out the reference:

Here's a new answer for anyone who comes across this in the future.

this.upVector: THREE.Vector3 = new THREE.Vector3(0.0, 1.0, 0.0);
this.camera: THREE.PerspectiveCamera;
...
    this.camera.rotateX(
      -this.verticalRotationSpeed * this.mouseMovement.movementY
    );

    this.camera.rotateOnWorldAxis(
      upVector,
      -this.horizontalRotationSpeed * this.mouseMovement.movementX
    );

To rotate around the x-axis, we use rotateX() to rotate around the object's x-axis.

To keep the camera level with the ground, we use rotateOnWorldAxis() to rotate the camera around the world's up axis.

If we rotated the camera vertically around its own up axis, we would introduce unwanted rotations on the z and x axes, as the object's coordinate system may not align with the world's coordinate system (the final scene is rendered in the world coordinate system).

Rotating the camera around the world's vertical axis ensures that the camera's right vector stays parallel to the ground, keeping the camera level while rotating vertically.

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

Problem arising from apostrophe usage in Javascript OData request

In my current project, I have a text input field that passes a value through JS to fetch filtered data of names from a JSON file using OData query parameters. However, I've encountered an issue where if a name contains an apostrophe, it results in a ...

Retrieving the present precipitation amount from a Java Script API

I'm having some issues with extracting information from this list because I don't have much experience with JavaScript and APIs. The API I'm working with provides data for the current hour, but I'm struggling to retrieve that specific v ...

Error in jQuery submenu positioning issue

I am attempting to design a menu that opens when the parent element is clicked and closes when the mouse leaves the previously opened one. It should operate from left to right. Here is an example: <ul class="menuFirst"> <li><im ...

jQuery's making an error here - looks like matchExpr[type].exec is missing in action

Today, I encountered an error while running my code. Despite searching for guidance online, resources that could help me were hard to come by. Specifically, after crafting a few JavaScript functions, any attempt to use jQuery's methods on selectors r ...

Error: JSON encountered circular structure when attempting to serialize an object of type 'ClientRequest' with a property 'socket' that references an object of type 'Socket'

Encountering an error while attempting to make a POST request to my TypeORM API using axios: TypeError: Converting circular structure to JSON --> starting at object with constructor 'ClientRequest' | property 'socket' -&g ...

A ServiceWorker used a promise in FetchEvent.respondWith() that resulted in a non-Response value of 'undefined'. This caused an issue in browser-sync

There are times when my server encounters an error in the console: Failed to load ‘http://localhost:3000/browser-sync/socket.io/?EIO=3&transport=polling&t=Lm2wn4p’. A ServiceWorker passed a promise to FetchEvent.respondWith() that reso ...

Tips on how to navigate to the end of a div that has been created through ng-repeat in Angular JS with the

Here is the template code I am working with: <div class="chatbox" id="mailBody" > <div class="panel-body" ng-repeat="mail in mails"> <div class="m-b-none" ng-if="mail.inboxMessageType == 1"> <a href class="pull-left ...

Using a combination of functions to ensure synchronicity in JavaScript operations

Here is the function I have created: $scope.saveManualResendDraft = function(todo) { if ($scope.editMode) { updateStartJobManual(); byeSendManualInputDirectly(); } else { console.log('bye'); } }; I have defin ...

What could be causing my YAML value to be undefined when I try to read it in JavaScript, despite it being defined in every other

I have been attempting to access a YAML file from my local directory. While I am able to read the file, the data within it appears to be undefined. The error message that I am encountering is as follows: https://i.sstatic.net/yXC0H.png Here is an exampl ...

How can I send a form without having the page reload using a combination of AJAX, PHP

I am struggling to submit a form without refreshing the page. I have tried using ajax as mentioned in some resources, but it's not working for me. What could be the issue? When I use the following code, everything works fine with PHP: document.getEl ...

Exploring the functionalities of can-deactivate without incorporating routing

I'm facing an issue with a parent component and multiple child components. The parent component contains a form, while each child component also has its own form. Unfortunately, all child components share the same route as the parent component and hav ...

What is the best way to incorporate camera.lookAt animation with gsap?

When using three.js, the camera.lookAt(myObject) function can rotate the camera towards a specified object. If you want to animate this rotation using gsap, you may encounter some challenges. Below is an example of code that attempts to animate the camera ...

Execute script when the awaited promise is fulfilled

I am looking to retrieve the URL of a cat image using the Pexels API through a script, and then set that image link as the source of an actual image element. I attempted to include some loading text to keep things interesting while waiting for the image l ...

JavaScript Array Objects

As a newcomer to the world of Javascript, I've decided to take on the challenge of creating a blackjack game. Utilizing arrays and objects for my game: card = {}, //each card is represented as an object with suit, number, and points properties playe ...

Exploring VueJs 3: Strategies for loading and implementing actions on a component before mounting

Briefly: Can a virtual node be created outside of the DOM to preload images, seek videos... without ever being mounted in the real DOM? Detailed version: I want to ensure that the next slide appears only when it is fully initialized for a slideshow in Vu ...

Leveraging a combination of AngularJS directives within a single div element

Why can't I use multiple directives in the same div tag in AngularJS? The product names from the module are not displayed with the following HTML code: <!DOCTYPE html> <html ng-app="gemStore"> <head> <title></ti ...

Tips for showcasing information from the tmdb api by leveraging the value or data obtained from a separate api

I am currently working on a project that involves displaying movie data using the tmdb api. I receive the response from my own api which only includes the id of the tmdb movie. Here is an example of the response: [ { "id": 0, "tit ...

Creating a Node API that can patiently listen for external data

My current project involves building a server that fetches data from an external API and returns it to the endpoint localhost:3000/v1/api/. However, I'm facing a challenge where the data retrieval process takes approximately 2 seconds, leading to empt ...

Importing an image from the public folder in a nested directory with Next.js

My images are stored in the public directory and all of my code is located in the src folder. Usually, when I try to import an image from src/page/page.js like: /image/logo/logo-dark.png, it works. But when I am importing images from the src/component/cor ...

What is preventing my application (docker) from connecting to the database?

Encountering a frustrating issue here: I've developed a NodeJS application with a server listening on port number 3000. The app includes simple operations such as post, put, and read, which interact with a database running in a Docker Container on por ...