Whenever I rotate my camera by 180 degrees, the keyboard controls in my Three.js application start malfunctioning

I have developed a keyboard control function using Three.js that functions correctly when the camera is facing north, east, or west. However, when it turns to face south, southeast, or southwest, the controls become reversed.

    if(controls["KeyW"]){ // w
      camera.position.x -= Math.sin(camera.rotation.y) * player.speed;
      camera.position.z -= -Math.cos(camera.rotation.y) * player.speed;
    }
    if(controls["KeyS"]){ // s
      camera.position.x += Math.sin(camera.rotation.y) * player.speed;
      camera.position.z += -Math.cos(camera.rotation.y) * player.speed;
    }
    if(controls["KeyA"]){ // a
      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(controls["KeyD"]){ // d
      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(controls["Space"]) { // space
      if(player.jumps) return false;
      player.jumps = true;
      player.velocity = -player.jumpHeight;
    }
  }

To help you better understand the issue I've been encountering, please visit my website through this link. My hypothesis is that the sine and cosine values may reverse after a 180-degree rotation.

Answer №1

After realizing my mistake, I discovered that instead of using pointer controls for mouse navigation and keyboard triggers to move around, I could utilize the built-in functions of PointerLockControls known as moveForward and moveRight.


  const mouseControls = new PointerLockControls(camera, renderer.domElement);
  document.addEventListener( 'click', () => {
    mouseControls.lock()
  }, false)

  const keysDown: any = {
    "KeyW": 0,
    "KeyA": 0,
    "KeyS": 0,
    "KeyD": 0,
  }

  document.addEventListener("keydown", ({ code }) => {
    keysDown[code] = 1 
  })
  document.addEventListener("keyup", ({ code }) => {
    keysDown[code] = 0
  })

  function updateControls() {
    const forwardDirection = keysDown["KeyW"] - keysDown["KeyS"];
    const rightDirection = keysDown["KeyD"] - keysDown["KeyA"];
    mouseControls.moveForward(forwardDirection * player.speed)
    mouseControls.moveRight(rightDirection * player.speed)
  }

  ////////main animation function
  function animate() {
    requestAnimationFrame( animate );
    updateControls();
    renderer.render( scene, camera );
  };

  animate();

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

Validating image dimensions with the data-parsley plugin

Is there a way to validate image dimensions with data-parsley? I attempted the code below, but it is not working. data-parsley-dimensions-options='{ "min_width": "100", "max_width": "100", "m ...

Angular 10 does not reflect changes in the array when they occur

My component receives an array of offers from an Observable. However, when the list is modified (a offer is deleted), the component's list does not update accordingly. I attempted to use ngOnChanges to resubscribe to the list and update it in my comp ...

Update data dynamically on a div element using AngularJS controller and ng-repeat

I am currently navigating my way through Angular JS and expanding my knowledge on it. I have a div set up to load data from a JSON file upon startup using a controller with the following code, but now I am looking to refresh it whenever the JSON object cha ...

No matter the way I input the URL in the AJAX call, the response always comes back as successful

I ran into an issue with my ajax request. It was supposed to be a GET request that returned some data, but no matter how I configured the URL, it always gave a success response even when it didn't actually succeed. var id = 5; $.ajax({ type: ...

The search functionality in Select2 is unresponsive when using Bootstrap 5

I am struggling with clicking on the search input dropdown. I have already searched online and found that this is a common issue with select2 in combination with bootstrap3 or bootstrap4. However, with bootstrap5 it seems to be a bit different (I had succe ...

Tips for dynamically loading images in React with a Collage component

It appears that all the examples I've come across are static in terms of loading images. While the code works, it does not display the divider <div> tag as expected. Instead, the results (images) are shown stacked in the first item of the Collag ...

The function you are trying to call in Javascript is currently unavailable

I encountered an issue with a JavaScript script. I have an object that contains some functions and variables. Within one of these functions, I make an Ajax request. However, in the error handler, when trying to call a function defined within the same objec ...

Having trouble with installing Recharts through npm

When I try to install recharts using npm, I encounter the following error message in my console: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! ...

"Unexpected outcome: Angular's HTTP request for a JSON file yields an undefined

Learning Angular has been a challenging experience for me. I am currently working on reading a json file into a chart on my main app page to visualize temperature data from my PI. Despite trying various methods found online, I have not been successful so f ...

Can I obtain a link through the branch_match_id parameter?

Within my application, there exists a hyperlink: hxxp://get.livesoccer.io/IuKk/0CRq5vArLx which leads to the following destination: hxxp://livesoccer.io/news.html?url=http%3A%2F%2Fwww.90min.com%2Fembed%2Fposts%2F4003374-chelsea-star-pedro-loving-life-at-s ...

How can I employ Single Sign-On (SSO) for my-website's account across various websites?

I'm looking to create a gaming platform similar to Epic Games, which we'll call "AB." I'd like game developers to be able to connect their games with my website and offer a "Login With AB" option on their login pages. Is this feasible? Thank ...

Ways To Create Multiple HTML Players

After successfully creating an audio player with html, css and javascript, I now face the challenge of adding multiple players to a single page. However, when attempting to play any player besides the first one, it only plays the initial player. How can ...

iOS Devices Experiencing HTTP 500 Error with JS Files and Libraries

I have encountered a puzzling issue with my web application. While it runs smoothly on PC devices without any errors, I am facing HTTP 500 errors when running it on iOS and inspecting it using Safari's Web Inspector. Specifically, I am seeing these er ...

The installation process with Npm seems to be dragging and I'm seeing a significant number of "cache misses" for almost every library

Everything seems to be functioning smoothly on my local computer. However, when I run nodejs inside a docker container (docker run node:18) and clone a project, the process of typing npm install to download all libraries becomes extremely slow. It takes ar ...

The tooltip content is a little too narrow

I have successfully implemented QTip2 to display a tooltip: The content of the tooltip is generated in the following method: public string GetHours() { DateTime d = Convert.ToDateTime(Request.Form["date"]); Bump b = new Bump(); ...

Removing a user via Fetch API in the delete endpoint

Creating a user website that allows the admin to delete users is my latest project. I've implemented it using an Azure SQL database and have set up an endpoint called deleteUser in my controllers file. deleteUser const deleteUser = (req, res) => { ...

Duplicate the identical data retrieval query, this time utilizing a JavaScript Ajax post method

To enhance the data request query, implement a JavaScript Ajax post method to avoid page refresh when the button is pressed. This will allow for requesting another page and displaying it in a designated section on the webpage. Here's the code snippet ...

Forcing ng-dirty in AngularJS form validation

When using AngularJS for form validation, I want all required fields to be marked as erroneous when the user clicks submit. To achieve this, I am utilizing input.ng-dirty.ng-invalid to style the controls with errors. My goal is to set ng-dirty on required ...

Issue: unable to spawn process due to missing file or command (Snapchat NPM) in NodeJS environment

Every time I start my app, I encounter the following error: events.js:72 throw er; // Unhandled 'error' event ^ Error: spawn ENOENT at errnoException (child_process.js:980:11) at Process.ChildProcess._handle.onexit ...

Transforming an HTML Java script for compatibility with ASP.Net using C#

Hey there! I've been given the task of converting a page from HTML to aspx, and I'm happy to say that I've successfully completed it. However, my main challenge now is getting a javascript function to run when the submit button is clicked. ...