繁体   English   中英

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

[英]Three.js - How to Pivot Camera around a Vector3 point?

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

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

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

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

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

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

如图所示

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

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

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

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

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

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

它的工作原理是应用旋转矩阵始终围绕原点旋转对象。 这与仅修改rotation属性形成对比, 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); } 
 html, body, #canvas { margin: 0; padding: 0; width: 100%; height: 100%; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r77/three.js"></script> <canvas id="canvas"></canvas> 

标准方法是将var camera_pivot = new object3D()创建到与对象相同的位置。 将相机放在孩子身上,将相机移回可观察的距离并旋转物体。

您可以根据需要移动object3D()并旋转。 它是简单代码和性能的最佳解决方案。

在object3D上你可以使用camera_pivot.translateX(),camera_pivot.rotateX(),camera_pivot.lookAt(obj)等...

其他方式很难做任何操作而不影响场景中的另一个对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM