How to rotate a 3D camera around an object

I make this program where you can click on an object, zoom in and then look at it from all angles by holding down the right mouse button and dragging. I need a camera to walk around an object, not rotate the object while looking at the camera. I honestly just don't know how to do it!

For testing, there is already a game object with xyz, which we have selected, and we 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));

      

Thus, the radius between the camera and the object is 500, and when selecting and rotating, the camera should always be at a distance of 500 from.

I am updating 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 to rotate this camera around g with a radius of 500?!?!

+3


source to share


1 answer


As gaitat mentioned, trackball control is the best place to start with many customizable options to make camera rotation / revolution easy. One huge potential advantage of this method (especially for your project) is to avoid the "gimbal lock", which is a source of great frustration when working with turns. Here's a link that can help you with Trackball and Orbitcontrols controls:

Rotate camera in Three.js with mouse

Another option would be to adjust the camera coordinates in the animation loop, which is actually pretty 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 is to connect the camera to the rotation object and just rotate the rod:

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're chasing this option, keep in mind that the camera object is in "camera rotation space" and may be more difficult to manipulate further.

+3


source







All Articles