# Three.js camera turning leftside right

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?

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

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;

var radius = Math.sqrt(x*x + z*z);
}


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