How do I adjust the controls in Three.js to align with the previous camera position?

The three.js scene is equipped with W,A,S,D and left and right arrow controls, which allow for movement of the camera. However, the controls restrict the camera's movement to a fixed direction in the scene, rather than relative to its previous position. These controls follow the standard gaming WASD setup, with W moving the camera forward. Visit the live example on CodePen: https://codepen.io/anon/pen/eydRea

var keyboard = {};
    var player= {height:30, speed:10, turnSpeed:Math.PI*0.02};  if(keyboard[87]){ // W key
    camera.position.x -= Math.sin(camera.rotation.y) * player.speed;
    camera.position.z -= -Math.cos(camera.rotation.y) * player.speed;
}
if(keyboard[83]){ // S key
    camera.position.x += Math.sin(camera.rotation.y) * player.speed;
    camera.position.z += -Math.cos(camera.rotation.y) * player.speed;
}
if(keyboard[65]){ // A key
    camera.position.x += Math.sin(camera.rotation.y + Math.PI/2) * player.speed;
    camera.position.z += -Math.cos(camera.rotation.y + Math.PI/2) * player.speed;
}
if(keyboard[68]){ // D key
    camera.position.x += Math.sin(camera.rotation.y - Math.PI/2) * player.speed;
    camera.position.z += -Math.cos(camera.rotation.y - Math.PI/2) * player.speed;
}

if(keyboard[37]){ // left arrow key
    camera.rotation.y -= player.turnSpeed;
}
if(keyboard[39]){ // right arrow key
    camera.rotation.y += player.turnSpeed;
}

Answer №1

To begin, determine the direction in which the camera is facing and then move the camera in that same direction. You can find more information on the direction to which the camera is facing by following this link.

For a working example based on your code, click here.

if(keyboard[87]){ // W key
      var matrix = new THREE.Matrix4();
      matrix.extractRotation( mesh.matrix );
      let axis = new THREE.Vector3(0,0,-1);
      axis = matrix.multiplyVector3(axis);
      camera.translateOnAxis(axis,player.speed);
      }
if(keyboard[83]){ // S key
      var matrix = new THREE.Matrix4();
      matrix.extractRotation( mesh.matrix );
      let axis = new THREE.Vector3(0,0,1);
      axis = matrix.multiplyVector3(axis);
      camera.translateOnAxis(axis,player.speed);
}
if(keyboard[65]){ // A key
      var matrix = new THREE.Matrix4();
      matrix.extractRotation( mesh.matrix );
      let axis = new THREE.Vector3(-1,0,0);
      axis = matrix.multiplyVector3(axis);
      camera.translateOnAxis(axis,player.speed);
}
if(keyboard[68]){ // D key
      var matrix = new THREE.Matrix4();
      matrix.extractRotation( mesh.matrix );
      let axis = new THREE.Vector3(1,0,0);
      axis = matrix.multiplyVector3(axis);
      camera.translateOnAxis(axis,player.speed);
}

if(keyboard[37]){ // left arrow key
    camera.rotation.y -= player.turnSpeed;
}
if(keyboard[39]){ // right arrow key
    camera.rotation.y += player.turnSpeed;
}

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

retrieving data from array elements

{ "success": true, "users": [ { "photo": { "id": "users/m1ul7palf4iqelyfhvyv", "secure_url": "https://res.cloudinary.com/dpbdw6lxh/image/upload/v1665251810 ...

Unable to employ the executescript method in Selenium with multiple arguments

I am currently working on automating a website to create a list through input values in a text field and setting them by clicking outside the field. Due to slow performance with Internet Explorer, I am using Selenium webdriver with IE. The sendKeys method ...

Having numerous calls to isNaN within a JavaScript if-else statement

I've created a JavaScript function that generates div elements and styles them based on user input values. However, I'm facing an issue when trying to display a warning message if the input is not a number. Currently, I'm unable to create th ...

The Material UI slider vanishes the moment I drag it towards the initial element

After moving the Material UI Slider to the initial position, it suddenly vanishes. via GIPHY I've spent 5 hours attempting to locate the source of the issue but have not had any success. ...

Updating specific data in MongoDB arrays: A step-by-step guide

{ "_id":{"$oid":"5f5287db8c4dbe22383eca58"}, "__v":0, "createdAt":{"$date":"2020-09-12T11:35:45.965Z"}, "data":["Buy RAM","Money buys freedom"], & ...

Ensure that every HTML link consistently triggers the Complete Action With prompt on Android devices

After extensive searching, I have yet to find a solution to my issue. I have been developing a web application that allows users to play video files, primarily in the mp4 format. Depending on the mobile browser being used, when clicking the link, the vide ...

### Setting Default String Values for Columns in TypeORM MigrationsDo you want to know how to

I'm working on setting the default value of a column to 'Canada/Eastern' and making it not nullable. This is the current setup for the column: queryRunner.addColumn('users', new TableColumn({ name: 'timezone_name', ...

Await that's locked within a solo asynchronous function

async function submitForm(e){ e.preventDefault() console.log(e.target) try { const response = await axios.post('/api/<PATH>', {username, password}); console.log(response.data); const token = response.data.token if (t ...

What is the purpose of sorting an object using the sequence defined in an array?

Have you ever wondered how the sortWeekFunction function can rearrange an object based on a predefined array order? It may seem complex at first glance, but let's break down how this code actually works. const weeksArr = ['sunday', ' ...

I am unable to enter any text in an angular modal

Currently, I am facing an issue where I am unable to click on the search input field within a modal. The goal is to implement a search functionality in a table displayed inside a modal window. The idea is to have a list of hospitals where users can view d ...

steps to create a personalized installation button for PWA

Looking to incorporate a customized install button for my progressive web app directly on the site. I've researched various articles and attempted their solutions, which involve using beforeinstallprompt. let deferredPrompt; window.addEventListener(& ...

Transferring a zipped file between a Node.js server and a Node.js client

I am facing an issue with sending a zip file from a node.js server to a node.js client. The problem is that when I try to save the zip file, it becomes corrupted and cannot be opened. To create and send the zip file to the client, I am using the adm-zip l ...

dividing an HTML string into individual variables using JavaScript

How can a string be split in pure JavaScript (without using JQuery/dojo/etc) in the most efficient and straightforward way? For example: var tempString = '<span id="35287845" class="smallIcon" title="time clock" style="color:blue;font-size:14px;" ...

Exploring an array to retrieve a specific value

Can someone assist me? I am looking to create a JavaScript function that follows the structure of the code example below. Unfortunately, I do not have enough programming skills to develop a functional solution from scratch. The goal is to input a value, ...

Guide on implementing ng-repeat within a nested JSON structure in your Ionic app

Struggling with implementing ng-repeat in a nested json object. { "title": "Important message 01", "img": "any url image here", "authorPhoto": "http://lorempixel.com/40/40/people/4/", "author": "John Doe", "datePos ...

Find a specific row in a table using jQuery without requiring any input from the

I want to create a search function that filters results in a table based on user input. The script I have currently works but I need it to only search the first column without requiring the user to click an input field. I want the default value to load whe ...

Having trouble with Redux's mapStateToProps function?

I'm working on a React component that triggers an AJAX call in the componentWillMount lifecycle method and then stores the fetched data in a Redux store. Here's the code snippet: componentWillMount() { var self = this; var xmlhttp = new XMLH ...

Troubleshooting: Issues with jQuery's Class selector

Having trouble setting up an alert to trigger when a specific class anchor tag is clicked inside a div. This is what my HTML section looks like... <div id="foo"> <a class='bar' href='#'>Next</a> </div> And h ...

Issues may arise in TypeScript when you are working with an array of objects along with other properties within a type

I am encountering an issue with an object structure similar to the one below: let Obj = { ['0'] : { mode: 'x' }, getMode: () => 'x' } The problem arises when I attempt to create a type definition as shown here: type Obj = ...

I'm curious, what is the optimal method for arranging a json object based on an index contained in each of its properties?

I'm working with an array of objects, looking like this myArray = [ { id: 3, data: foo }, { id: 7, data: bar } ] However, I would like to transform it into the following structure transformedArray = { 3: ...