当我将相机旋转 180 度时,我的三个 js 键盘控件无法正常工作

my three js keyboard controls dont work correctly when i turn my camera around 180 degrees

我已经实现了一个 threejs 键盘控制功能,只要相机朝向北、东或西方向,它就可以正常工作,当它转向南、东南或西南时,控件会自行反转

    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;
    }
  }

为了更好地帮助您理解我一直面临的问题,这里有一个 link 我的网站,我的猜测是 sin 和 cos 在旋转 180 度后反转它们的值

好吧,我犯的错误是我使用指针控件进行鼠标导航和键盘触发器来四处移动,稍微研究了文档并意识到我可以使用名为 moveForward 的 PointerLockControls 的内置函数和 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();