What is the method for adjusting the camera without being restricted by its axes?

I've modified some code from the example at to create a simplified version without certain elements like flying cubes and jumping:

var camera, scene, renderer, controls;
var objects = [];
var raycaster;
var moveForward = false;
var moveBackward = false;
var moveLeft = false;
var moveRight = false;
var canJump = false;
var prevTime = performance.now();
var velocity = new THREE.Vector3();
var direction = new THREE.Vector3();
var vertex = new THREE.Vector3();
var color = new THREE.Color();

// Rest of the initialization and setup code
...

The current movement logic in the example has a limitation where looking down slows down movement. To fix this issue, I want to make the movement independent of the camera angle.

One solution could be changing the lines

controls.getObject().translateZ(Number( moveBackward ) - Number( moveForward ));
controls.getObject().translateX(Number( moveRight ) - Number( moveLeft ));

to

controls.getObject().position.z += Number( moveBackward ) - Number( moveForward );
controls.getObject().position.x += Number( moveRight ) - Number( moveLeft );

This adjustment works initially but introduces a new problem where movement direction changes when the camera rotates. How can I achieve movement along the z/x axis while still moving in the camera's direction independent of its angle, avoiding slowdowns when looking up or down?

Answer №1

To determine the camera's direction in world space, you can utilize the method controls.getDirection(). It is important to normalize the x and z components in order to prevent vertical rotation from impacting your movement.

For lateral movement, it is recommended to use a vector that is perpendicular to d (simply interchange its components and multiply y by -1).

Instead of using:

controls.getObject().translateZ(Number( moveBackward ) - Number( moveForward ));
controls.getObject().translateX(Number( moveRight ) - Number( moveLeft ));

You should replace it with:

var cameraDirection = new THREE.Vector3();
controls.getDirection(cameraDirection);

var d = new THREE.Vector2(
    cameraDirection.x,
    cameraDirection.z
);

d.normalize();

controls.getObject().position.x -= d.x * (Number(moveBackward) - Number(moveForward));
controls.getObject().position.z -= d.y * (Number(moveBackward) - Number(moveForward));

controls.getObject().position.x -= d.y * (Number(moveRight) - Number(moveLeft));
controls.getObject().position.z += d.x * (Number(moveRight) - Number(moveLeft));

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

Vue.js: The v-for directive demonstrates distinct behavior with the utilization of template literals

What is the difference in behavior of v-for when using numbers versus template literals? Consider the following scenario: new Vue({ el: "#app", }) <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div i ...

Having trouble with the cookie functionality in Ionic Angular JS?

app.js angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ngCordova', 'ngCookies']) .run(function ($ionicPlatform) { $ionicPlatform.ready(function () { if (window.c ...

Create a custom CSS style to replace the default jQuery hide() function

HTML <div class="adm-input" <?php if(!empty($admin_fee) || $admin_fee != "") echo "style='display:block'"; ?> id="fees-input"> <label>Admission Fees(<i class="fa fa-inr"></i>)</label> <div class="in ...

The method expression does not match the Function type specified for the mongoose Model

Encountered a perplexing error today that has eluded my attempts at finding a solution. const mongoose = require('mongoose'); const userSchema = mongoose.Schema({ name: {type:String, required:false}, birthday: {type:String, required:f ...

Issue with functionality of Bootstrap 4 Checkbox accordion

I am trying to achieve something similar to this example: https://getbootstrap.com/docs/4.0/components/collapse/#multiple-targets Instead of using a button, I want to use a checkbox. I want the collapse effect to occur when the checkbox is checked. < ...

What could be causing my Vue.js sorting array script to malfunction?

I'm encountering an issue with sorting the table by Date. The sort function used to determine the type of sorting no longer works, and I'm unsure why. html: <th @click = "sort('data_produktu')" class="date">Da ...

Pass data to child component in react

I have a parameterized component that can take a value of true or false, and I'm using console.log to verify it. console.log(isContract); //can be true or false Now, I need to pass this value through a form to render another component. This is the p ...

Encountered an issue while configuring mapping upload for Bugsnag within a React Native project

I'm in the process of incorporating Bugsnag into my React Native project. I want to make sure that any stack traces point to the correct section of the code. However, due to the need for a release app to obtain a stack trace, the source mappings are m ...

Unexpected syntax error encountered when shutting down the route, unable to recover

const express = require('express'); const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.get('/split/name', (req, res) => ...

Can the submit ID value be utilized in PHP?

name="submit" functions as expected. if(isset($_POST["submit"])) <input type="submit" ID="asdf" name="submit" value="Save" class="ui blue mini button"> I want to change it to use ...

Automatically refresh the div as soon as a new entry is added to the database

I am attempting to extract all the data rows from a table that existed before the user visited the page and then update the div with any new rows of data that have been added to the table since the user's visit (similar to how WhatsApp displays conver ...

jQuery scripts were not loaded, resulting in an uncaught type error

Hey there! I am currently using jQuery Tablesorter to handle pagination on my website, but it seems to be throwing an error in the browser console. The specific error message reads: Uncaught TypeError: undefined is not a function viewTags:24 (anonymous fu ...

Data retrieval takes precedence over data insertion

I'm facing an issue where I am trying to insert data into MySQL using Knex within a loop, but the data retrieval is happening before the insertion. Can anyone assist me with this problem? for (let i = 0; i < fileArray.length; i++) { fileLocation ...

Skipping a JSON field in HTML/JavaScript when it is blank: A guide for developers

To develop an interactive program based on JSON input, I aim to display headers, subheaders, and choices derived from the JSON data. Some input fields may remain unfilled. For instance: Header Subheader Choice 1 Choice 2 Subheader2 Choice ...

Using webGL for rendering drawElements

I am working with face-indices that point to specific points to draw triangles in a loop. Unfortunately, when executing my code, I encountered the following error in the web console: WebGL: drawElements: bound element array buffer is too small for given c ...

Discover the potential location of an element using jQuery's animate feature

Struggling to obtain the correct position of an element due to the length of my animation causing $(this).position().top to be calculated prematurely. Is there a way to predict the future position value of an element before it moves to that specific locat ...

Steer clear of receiving null values from asynchronous requests running in the background

When a user logs in, I have a request that retrieves a large dataset which takes around 15 seconds to return. My goal is to make this request upon login so that when the user navigates to the page where this data is loaded, they can either see it instantly ...

Show fixed div at specific height

Is there a way to have a fixed title in a DIV that only displays once the user scrolls to the relevant section on the website? I'm looking for a solution where the DIV is hidden until the section is reached during scrolling. ...

Identify when a mouse hovers within 10 pixels of a div using jQuery

Is it possible to detect when a user hovers over a specific area within a div using JavaScript or jQuery, without adding any additional tags? -------------------------------- -------------------------------- -------------------------------- -------- ...

Exploring the possibilities of using React for looping?

I have integrated Dexie.js with React for this specific example. However, the implementation details are not of great importance to me. My main focus is on finding out how to iterate through all objects in my IndexDB database using React. In the code snip ...