0
votes

In Three.js I am trying to implement an orbiting camera can be rotated around the x and the y axis. I am using these two functions:

    function rotateX(rot) {
        var x = camera.position.x,
            y = camera.position.y,
            z = camera.position.z;

        camera.position.x = x * Math.cos(rot) + z * Math.sin(rot);
        camera.position.z = z * Math.cos(rot) - x * Math.sin(rot);

        camera.lookAt(scene.position);
    }

    function rotateY(rot) {
        var x = camera.position.x,
            y = camera.position.y,
            z = camera.position.z;

        camera.position.z = z * Math.cos(rot) + y * Math.sin(rot);
        camera.position.y = y * Math.cos(rot) - z * Math.sin(rot);

        camera.lookAt(scene.position);     
    }

Now the x rotation works fine but the y rotation does not. Once I go over the top of the model as in that the camera's z position becomes negative then suddenly the lookAt method rotates the camera by PI amount on the Z axis and suddenly the left side of the model is on the right and vice versa. Now I can fix this by checking for a negative Z and then just fixing the camera's rotation but this then causes a malfunction when using x ad y rotation at the same time, the x then suddenly gets this inverting behavior.

How should I go about fixing this?

1

1 Answers

1
votes

The problem you are experiencing is called Gimbal lock. You need to use quaternions in order to solve it. You can read about it here https://gamedev.stackexchange.com/questions/45292/how-is-the-gimbal-locked-problem-solved-using-accumulative-matrix-transformation