Leprosy
Leprosy

Reputation: 1135

THREE.js - Rotate the camera just like trackball controls

I'm using Trackball controls in a scene and I want to implement a function to rotate the camera just like the way dragging the mouse in the canvas does it. How can I accomplish something like that? I've been looking the code of the Trackball control module, but I can't find something to start.

EDIT: I've been looking several pages, the THREE documentation and whatnot, but still can't reproduce the Trackball style rotation. I've been using quaternions too but they can't reproduce the behavior(or I'm missing something, most probably). Any help?

EDIT 2 : What I'm looking for is a way to do something like this:

function rotateCam(angle) { // code }

var angle = 0.01; //some value
rotateCam(angle);
$('#button').addEventListener('mousedown', function() { rotateCam(angle); } );

Where button is an HTML element representing a button.

Upvotes: 2

Views: 5199

Answers (3)

Leprosy
Leprosy

Reputation: 1135

I noticed that the Trackball controls, apart of rotate via quaternion, do a zoom to correct some distances. I tried to read the code, and got this:

function rotate(L) {
    var vector = controls.target.clone();
    var l = (new THREE.Vector3()).subVectors(camera.position, vector).length();
    var up = camera.up.clone();
    var quaternion = new THREE.Quaternion();

    // Zoom correction
    camera.translateZ(L - l);

    quaternion.setFromAxisAngle(up, 0.015);
    camera.position.applyQuaternion(quaternion);
    camera.lookAt(vector);
    renderer.render(scene, camera);
}

Works like a charm...hope someone find this useful too. ;)

Upvotes: 3

ABN
ABN

Reputation: 101

function cameraRotate(distance, angle){

            camera.position.x = distance * Math.cos( angle );
            camera.position.z = distance * Math.sin( angle );

}

This would rotate your camera at the specified distance and angle around the scene. If you want a smooth rotation you could call this with a small angle increase from the animate-loop, depending on input for example.

Upvotes: 1

Leprosy
Leprosy

Reputation: 1135

I'm on the right way I think...I did this:

function rotate() {
    if (this.showCase) {
        var vector = controls.target.clone(); // controls is a TrackballControls
        var up = camera.up.clone();
        var quaternion = new THREE.Quaternion();
        quaternion.setFromAxisAngle(up, 0.015);
        camera.position.applyQuaternion(quaternion);
        camera.lookAt(vector);
        renderer.render(this.scene, this.camera);
    }
},

Still, it doesn't look right right like the TrackballControls rotation.

Upvotes: 0

Related Questions