如何旋转三.透视对象周围的摄像机

How to rotate a THREE.PerspectiveCamera around on object

本文关键字:对象 透视 周围 摄像机 何旋转 旋转      更新时间:2023-09-26

我正在制作这个程序,您可以在其中单击一个对象,缩放到它,然后通过按住鼠标右键并拖动从各个角度查看它。我需要相机围绕物体移动,而不是在相机看着物体的情况下旋转物体。老实说,我只是不知道如何计算它!

为了进行测试,已经有一个带有 xyz 的游戏对象,我们已经选择并正在查看

var g = new GameObject(500, 0, 0);//The game object with xyz
this.selected = g;//set selected to g
//Create and set the camera
this.camera = new THREE.PerspectiveCamera(45, w/h, 1, 10000);
this.camera.position.x = 0;
this.camera.position.y = 0;
this.camera.position.z = 0;
//set camera to look at the object which is 500 away in the x direction
this.camera.lookAt(new THREE.Vector3(this.selected.x, this.selected.y, this.selected.z));

因此,相机和对象之间的半径为 500,并且在选择和旋转时,相机应始终在 500 之外。

我在这里更新场景:

Main.prototype.update = function(){
    this.renderer.render(this.scene, this.camera);//scene is just some ambient lighting
    //what to do when mouse right is held down
    if(this.rightMouseDown){
        //placeholder functionality, needs to rotate around object based on mouse movements
        this.camera.position.x -= 5;
    }
}

如何以 500 的半径围绕 g 旋转此相机?!?!

正如 gaitat 所提到的,轨迹球控制是使用许多可配置参数开始的最佳位置,以使摄像机旋转/旋转变得容易。这种方法的一个巨大潜在好处(特别是对于你的项目)是避免"万向节锁定",这是使用旋转时很多挫败感的来源。以下链接可能会对轨迹球控件和轨道控件有所帮助:

用鼠标旋转相机三.js

另一种选择是在动画循环中自己设置摄像机坐标,这实际上非常简单:

var angle = 0;
var radius = 500; 
function animate() {
...
// Use Math.cos and Math.sin to set camera X and Z values based on angle. 
camera.position.x = radius * Math.cos( angle );  
camera.position.z = radius * Math.sin( angle );
angle += 0.01;
...
}

另一种选择是将相机连接到枢轴对象,然后旋转枢轴:

var camera_pivot = new THREE.Object3D()
var Y_AXIS = new THREE.Vector3( 0, 1, 0 );
scene.add( camera_pivot );
camera_pivot.add( camera );
camera.position.set( 500, 0, 0 );
camera.lookAt( camera_pivot.position );
...
camera_pivot.rotateOnAxis( Y_AXIS, 0.01 );    // radians

如果选择此选项,请注意相机对象位于"相机枢轴空间"中,并且进一步操作可能更具挑战性。