Three.js - 如何修复控件与最后一个摄像头位置相关的工作?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Three.js - 如何修复控件与最后一个摄像头位置相关的工作?相关的知识,希望对你有一定的参考价值。

three.js场景具有W,A,S,D和左右箭头控件。控件移动相机但仅在场景中的固定方向上而不是相对于最后一个相机位置。控制是W向前推进的标准游戏。查看实时代码集示例: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;
}
答案

您需要做的是首先获取摄像机所面向的方向并将摄像机转向该特定方向。然后按照此link获取摄像机所面向的方向。

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

以上是关于Three.js - 如何修复控件与最后一个摄像头位置相关的工作?的主要内容,如果未能解决你的问题,请参考以下文章

three.js之正投影摄像机与透视投影摄像机的区别

如何将fbxloader加载的摄像头添加到three.js中的场景?

如何在three.js场景中使对象仅对一台摄像机可见

three.js 围绕 Y 轴的相机旋转似乎关闭

深入理解Three.js中正交摄像机OrthographicCamera

Three.js如何在AR应用程序上触摸按钮时更改一个对象的两种材质