After spending a long night working with quaternions, I finally managed to implement mouselook functionality on a test game using three.js.
However, I quickly noticed that if I continue looking upwards, the camera ends up flipping upside down. I hastily put together some code that works fine when the user scrolls leisurely, but fails when scrolling fast. I suspect it's an issue with how I'm clamping the camera rotation. How can I correct this? Or maybe I was on the right track and just missed something obvious?
Check out the project here:
This is my camera rotation function:
//Rotate camera horizontally
y -= mouseMove.x * 0.02;
//Rotate camera vertically
//Check if moving camera up or down
if (mouseMove.y < 0) {
//Make sure it's not at top or bottom
if (Math.abs(camera.rotation.y*(180/Math.PI)) > 2 || camera.rotation.x <= 0){
x -= mouseMove.y * 0.02;
}
} else if (mouseMove.y > 0) {
if (Math.abs(camera.rotation.y*(180/Math.PI)) > 2 || camera.rotation.x >= 0){
x -= mouseMove.y * 0.02;
}
}
And here is my Update Camera function:
function updateCamera(){
camera.lastRotation = camera.quaternion.clone();
var euler = new THREE.Euler(0, 0, 0, 'YXZ');
euler.x = x;
euler.y = y;
euler.z = z;
mouseMove.x = 0;
mouseMove.y = 0;
camera.quaternion.setFromEuler(euler);
}
Here's an image illustrating the problem: