In my Three.js scene, I have a camera that I need to move and change its angle around a specific focal point. The focal point is actually the camera's position, and during rendering, I translate the camera by using the cameraBuff
vector to position it on a sphere and make it look at the focal point.
Everything works fine until I start moving the camera. At certain angles (vertical, 0 < x < 180), it seems to freeze and can't rotate around the focal point. When I slightly move it down, it starts working again. The issue arises when the cameraBuff
vector becomes perpendicular to the surface.
Here's the code snippet I use to rotate the cameraBuff
vector/point around the focal point:
// Mouse events *onDown* are recorded when the mouse is clicked
theta = -((event.clientX - mouse.onDownPosition.x) * 0.5) + mouse.onDownTheta;
phi = ((event.clientY - mouse.onDownPosition.y) * 0.5) + mouse.onDownPhi;
phi = Math.min(180, Math.max(0, phi));
cameraBuff.x = radius * Math.sin(theta * Math.PI / 360 ) * Math.cos( phi * Math.PI / 360 );
cameraBuff.y = radius * Math.sin(phi * Math.PI / 360 );
cameraBuff.z = radius * Math.cos(theta * Math.PI / 360 ) * Math.cos( phi * Math.PI / 360 );
Changing the line
phi = Math.min(180, Math.max(0, phi));
to phi = Math.min(160, Math.max(20, phi));
makes it work, but then I can't get the camera to be perpendicular to the surface or lower it.
For example, here's what happens when the 'w' key is pressed:
if (input.w)
{
var speed = [game.direction.x*60, game.direction.z*60];
game.camera.position.x -= speed[0]; // The camera position and focus are essentially the same point.
game.focus.x -= speed[0];
game.camera.position.z -= speed[1];
game.focus.z -= speed[1];
}
The direction is calculated as follows:
var c = Math.sqrt(cameraBuff.x*cameraBuff.x + cameraBuff.z*cameraBuff.z);
var rat = 1/c;
game.direction.x = cameraBuff.x*rat;
game.direction.z = cameraBuff.z*rat;
I'm struggling to figure out what's wrong with my code. Can someone please help explain?