Three.js - 如何围绕Vector3点旋转相机?

pan*_*kub 4 javascript trigonometry three.js vector-space

好的,我会尝试尽可能简洁.我对数学不是很了解,对你来说看起来很明显很可能对我来说是火箭科学.

我正在使用带有CSS3DRenderer的Three.js来创建虚拟图库空间.

我需要第一人称视角,就像FPS游戏一样.

我已经让相机成功向前,向后,向左和向右移动.

但是,当我去旋转相机时,我得到了结果 如图所示

相机正在旋转它的局部轴,但我需要的是viewport旋转,而不是相机

如图所示

所以我需要的是让摄像机绕枢轴点/矢量运行,然后使用重新聚焦 Object3d.lookAt()

我知道我可以通过将相机作为另一个对象的子节点,然后旋转对象的轴来解决我的问题.但是,我宁愿自己做数学.

简而言之,我想了解如何围绕另一个旋转一个矢量点,以及如何以数学方式表示该关系.

希望利用脚本,例如,three.js所pointer_lock控制,来完成这项工作.我想弄清楚实际数学.

任何建议或教程链接将不胜感激!

Bre*_*ble 6

下面是相机围绕盒子旋转的示例.

它的工作原理是应用旋转矩阵始终围绕原点旋转对象.这与仅修改rotation属性形成对比,该属性在您发现时围绕其自己的中心旋转对象.这里的技巧是将相机移动200个单位远离原点,这样当我们应用旋转矩阵时,它然后围绕原点旋转一圈.

由于盒子位于原点,这将使相机围绕盒子旋转.然后lookAt用于将相机指向盒子.

如果您想了解更多信息,请参阅以下有关该主题的简要说明:http://webglfundamentals.org/webgl/lessons/webgl-scene-graph.html

var canvas = document.getElementById('canvas');
var scene = new THREE.Scene();
var renderer = new THREE.WebGLRenderer({canvas: canvas, antialias: true});
var camera = new THREE.PerspectiveCamera(45, canvas.clientWidth / canvas.clientWidth, 1, 1000);

var geometry = new THREE.BoxGeometry(50, 50, 50);
var material = new THREE.MeshBasicMaterial({color: '#f00'});
var box = new THREE.Mesh(geometry, material);
scene.add(box);

// important, otherwise the camera will spin on the spot.
camera.position.z = 200;

var period = 5; // rotation time in seconds
var clock = new THREE.Clock();
var matrix = new THREE.Matrix4(); // Pre-allocate empty matrix for performance. Don't want to make one of these every frame.
render();

function render() {
  requestAnimationFrame(render);
  if (canvas.width !== canvas.clientWidth || canvas.height !== canvas.clientHeight) {
    // This stuff in here is just for auto-resizing.
    renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);
    camera.aspect = canvas.clientWidth /  canvas.clientHeight;
    camera.updateProjectionMatrix();
  }

  // Create a generic rotation matrix that will rotate an object
  // The math here just makes it rotate every 'period' seconds.
  matrix.makeRotationY(clock.getDelta() * 2 * Math.PI / period);

  // Apply matrix like this to rotate the camera.
  camera.position.applyMatrix4(matrix);

  // Make camera look at the box.
  camera.lookAt(box.position);

  // Render.
  renderer.render(scene, camera);
}
Run Code Online (Sandbox Code Playgroud)
html, body, #canvas {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r77/three.js"></script>
<canvas id="canvas"></canvas>
Run Code Online (Sandbox Code Playgroud)