Adjust camera view according to the rotation in three.js

I am in the process of creating a demonstration, and I'm facing an issue with moving the camera in my scene in the direction it is pointing. The concept is similar to pointer lock controls, but I need the camera to have the ability to move up, down, forward, backward, left, and right. Currently, I've been taking the camera's rotation and adding it to the position, but this method doesn't quite move the camera forward (relative to its perspective). It seems to be moving in an unexpected direction relative to the viewer, with the direction changing based on where you're looking. Here is the code snippet I've been using:

const rotation = this.internalCamera.rotation.toVector3();
const speed = 1;
this.internalCamera.position.add(
    new Vector3(
        rotation.x * speed,
        rotation.y * speed,
        rotation.z * speed
    )
);

I suspect that the issue may lie within the spatial system in three.js, but I'm not entirely sure. Can someone help me identify what mistake I've made?

Answer №1

The 'rotation' vector in your code is used to represent angles instead of coordinate measurements. To create a moving vector, you will need to multiply it with a rotation matrix based on your camera's direction.

// Define vector for left/right (x), up/down (y), forward/backward (z) movements
const vector = new Vector(x, y, z);

// Create rotation matrices
const rotx = (new THREE.Matrix4).makeRotationX(camera.rotation.x);
const roty = (new THREE.Matrix4).makeRotationY(camera.rotation.y);
const rotz = (new THREE.Matrix4).makeRotationZ(camera.rotation.z);

// Multiply all matrices together
const rotmat = rotx.multiply(roty).multiply(rotx).multiply(rotz);

// Apply the rotation matrix to the vector
vector.applyMatrix4(rotmat);

// Add the vector to the camera's position
camera.position.add(vector);

This revised code should function correctly. I have simplified some variable names for clarity; feel free to adjust them according to the actual variables in your script.

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

Effortlessly transfer files with Ajax through Box

I attempted to utilize the Box.com API for file uploads according to instructions from https://gist.github.com/seanrose/5570650. However, I encountered the following error message: `XMLHttpRequest cannot load "". No 'Access-Control-Allow-Origin&ap ...

Retrieving an array of various responses using Axios

My current code includes a function that retrieves exchange rates for various stocks: export const getRates = (symbole1, symbole2, symbole3) => { const res = [] axios.all([ axios.get(`${baseUrl}/${symbole1}`), axios.get(`${ ...

Customizing Drop Down Button in React Material-UI with Conditions

Trying to figure out how to dynamically populate the second MUI dropdown based on the selection from the first dropdown. Currently, I have both dropdown lists hardcoded. const [queryType, setqueryType] = React.useState(''); const [subCategory, se ...

What is the method for loading a subcategory based on the category by invoking a jQuery function within the <td> element of a JavaScript function that adds rows dynamically?

Whenever I click the add row button, the category dropdown list successfully loads. However, when I select an option from this category list, the subcategory does not load any list. The Javascript function responsible for adding rows dynamically is as fol ...

The automatic CSS cookie bar functions smoothly, but could benefit from a small delay

I successfully added a pure CSS cookie bar to my website, but there is a slight issue. When entering the site, the cookie bar is the first thing that appears, and then it goes up and down before settling at the end. How can I make my cookie bar only go do ...

What could be causing data to be saved twice when using a mongoose callback function?

Recently, I've been intrigued by the behavior of adding a callback to the mongoose findOneAndUpdate function and how it leads to saving data twice in the database. public async addPersonAsFavorite(userId: string, friendId: string) { if (!await th ...

Issues with the functionality of Google Translate's JavaScript code snippet are causing

After trying out the code snippet provided on w3schools.com, I encountered a discrepancy between the results displayed on the website and those on my personal computer. <div id="google_translate_element"></div> <script> function googleT ...

JavaScript returns the value 'undefined' when a function variable is used with an array of objects

Here is an example of an array of objects: var theArray = [ {theId:'1', num: 34}, {theId:'2', num: 23}, {theId:'5', num: 26} ]; This function successfully loops through the array: function printValues() { va ...

Using Angular to automatically update the user interface by reflecting changes made in the child component back to the parent component

Within Angular 5, I am utilizing an *IF-else statement to determine if the authorization value is true. If it is true, then template 2 should be rendered; if false, then template 1 should be rendered. Below is the code snippet: <div *ngIf="authorized; ...

The output.library.type variable in WebPack is not defined

Currently, I am delving into WebPack with a shortcode. As part of my learning process, I am working on a code snippet that involves calculating the cube and square of a number, which are then supposed to be stored in a variable outlined in the webpack.conf ...

Using socket.io to listen for events and wait for promises to resolve

I am facing an issue with a button that communicates with the server to verify if a value entered in an input box already exists. The current code is as follows: $("#button").click(function () { var exists = false; var name = $("#name").val(); ...

A step-by-step guide on closing a Bootstrap 5 Modal using JavaScript

Objective: I am trying to close a bootstrap 5 modal using JavaScript code after showing an alert message. Challenge: I am facing difficulty getting the function myFunction to work and subsequently closing the modal once the alert message is displayed ...

Utilize Vue.js to take screenshots on your device

After following the tutorial at https://www.digitalocean.com/community/tutorials/vuejs-screenshot-ui, I was able to successfully capture a screenshot with Vue.js. However, it seems that the dimensions of the screenshot are not quite right. Issue: The cap ...

Retrieving the checkbox value from a dropdown selection

I'm stuck and feeling lost here - I must be missing something obvious. Any help will be greatly appreciated! (I am a beginner in html and javascript) I have created a dropdown menu with an unordered list of items populated from JSON data. Here is the ...

Issue with Angular 5 - Deselect all checkboxes not reflecting in the UI

I am currently working on integrating a reset button into a Reactive form in Angular 5. The reset functionality works flawlessly for all form fields, except for the dynamically created multiple checkboxes. Although it seems like the reset operation is hap ...

Creating visualizations by overlaying shapes onto images using specified coordinates in jQuery

I have a web application in development that integrates with the skybiometry API. Their demo showcases a fantastic user feedback system displayed after facial recognition, similar to the one shown below. I am currently working on implementing a similar fe ...

Create a sinusoidal wave and stream it through the web browser

I'm looking for a code snippet that can: create a sine wave (an array of samples) play the wave This should all be accomplished in a web browser using an HTML5 API in JavaScript. (I've tagged this with web-audio, but I'm not entirely ...

What strategies can be used to prevent state mutations?

I am facing mutability for the first time. My state items consist of an object with keys like id, and using allIds I am trying to update specific id items with a new date. However, all items are being changed simultaneously, which I believe is due to mut ...

I am experiencing issues with the jQuery function within my MVC Application

When working on my MVC application, I encountered an issue where the onclick function was not functioning as expected. @section Scripts{ <script src="~/Scripts/plugins/toastr/toastr.min.js"></script> <script> $(document). ...

Unusual $http Angular.js POST inquiry

Hey there, I'm facing a peculiar issue in my web development project. I have a table that acts as an input field where users can enter data and then send it back to the Spring Rest API. The data is received as a String and then parsed using the Gson l ...