2
\$\begingroup\$

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?

\$\endgroup\$
2
  • \$\begingroup\$ Is this the same as the arcball camera problem? \$\endgroup\$ Commented Jul 8, 2014 at 15:09
  • \$\begingroup\$ @Anko I guess it could be but I am using touch for rotation so using absolute positions for rotation is not an option... \$\endgroup\$ Commented Jul 8, 2014 at 19:36

1 Answer 1

2
\$\begingroup\$

Your code is a little strange. If you want to rotate around the Y axis, then you change the X and Z coords, but you're altering Y and Z.

This code rotates smoothly around Y:

function rotateCameraY(radiansIncrement) {
var x = _camera.position.x; var y = _camera.position.y; var z = _camera.position.z;
var signx = x > 0 ? 1 : -1;

// get current radians from z and x coords.
var radians = x == 0 ? Math.PI/2 : Math.atan(z/x);
if (signx == -1) radians += Math.PI;

radians += radiansIncrement;
if (radians > Math.PI*2) radians = radians%(Math.PI*2);
while (radians < 0) radians += Math.PI*2;

var radius = Math.sqrt(x*x + z*z);
_camera.position.x = radius * Math.cos(radians);
_camera.position.z = radius * Math.sin(radians);
}

You can see it at work here: http://formulatoy.net

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.