如何围绕物体旋转THREE.PerspectiveCamera

And*_*her 5 javascript math rotation perspectivecamera three.js

我正在制作这个程序,您可以在其中单击一个对象,缩放到它,然后通过按住鼠标右键并拖动从所有角度查看它.我需要相机绕过物体,而不是用相机看着它旋转物体.老实说,我根本不知道如何数学出来!

为了进行测试,我们已经选择并正在查看一个带有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));
Run Code Online (Sandbox Code Playgroud)

因此,相机和物体之间的半径为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;

    }
}
Run Code Online (Sandbox Code Playgroud)

如何围绕g旋转此相机,半径为500?!?!

小智 5

正如盖塔特所说,轨迹球控件是从许多可配置参数开始的最佳位置,以使摄像机旋转/旋转变得容易。这种方法(尤其是对您的项目而言)的一个巨大的潜在好处是避免了“万向锁定”,这是旋转工作时倍受挫折的根源。这是一个可以帮助您使用轨迹球控件和Orbitcontrols的链接:

用鼠标在Three.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;
...
}
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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