How to rotate a THREE.PerspectiveCamera around on object

牧云@^-^@ 提交于 2020-01-02 04:33:10

问题


I am making this program where you can click on an object, zoom to it, then look at it from all angles by holding the right mouse button and dragging. I need the camera to be going around the object, not rotate the object with the camera looking at it. I honestly just have no idea how to math it out!

For testing there is already a game object with an xyz we have selected and are looking at

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

So the radius between the camera and the object is 500 and while selected and rotating, the camera should always be 500 away.

I update the scene here:

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;

    }
}

How do I rotate this camera around g with a radius of 500?!?!


回答1:


As gaitat mentioned, trackball controls are the best place to start with many configurable parameters to make camera rotation/revolution easy. One enormous potential benefit of this method ( especially for your project ) is avoiding "gimbal lock" which is the source of much frustration when working with rotations. Here's a link that might help you with Trackball controls and Orbitcontrols:

Rotate camera in Three.js with mouse

Another option would be setting camera coordinates yourself in the animation loop which is actually quite simple:

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

Another option would be to connect the camera to a pivot object and just rotate the pivot:

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

If you pursue this option, be aware that the camera object is in "camera pivot space", and might be more challenging to manipulate further.



来源:https://stackoverflow.com/questions/27095251/how-to-rotate-a-three-perspectivecamera-around-on-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!