Reputation: 32334
I have a simple Three.js scene around which I want to move the camera. The camera needs to be able not only just to move, but to change the angle around a certain focus point. The focus point is actually the camera position, and at the time of rendering, I actually just translate the camera by cameraBuff
and it places it on a sphere, and then I tell it to look at the focus point.
Until the camera is moved, everything works OK, I can rotate the camera and all that. But, once I start moving, something just seems to break! At normal angles (vertical, 0 < x < 180) it just freezes and cannot rotate around the focus point at all. Once I move it down a little bit, everything starts working again. Just to elaborate, the problems are happening once the cameraBuff
point become perpendicular to the surface.
This is the code I use to rotate the cameraBuff
vector/point around the focus:
//mouse.onDown* things are recorded once the mouse is initially pressed
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 );
Once I change phi = Math.min(180, Math.max(0, phi));
to phi = Math.min(160, Math.max(20, phi));
, for example, things work, but I am not able to even get the camera to be perpendicular to the surface, or even lower it.
This is what happens when, for example, w is pressed:
if (input.w)
{
var speed = [game.direction.x*60, game.direction.z*60];
game.camera.position.x -= speed[0]; //camera.position and focus are basically the same point all the time.
game.focus.x -= speed[0];
game.camera.position.z -= speed[1];
game.focus.z -= speed[1];
}
And the direction is calculated like this:
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;
Can someone explain what is wrong with my code?
Upvotes: 1
Views: 200
Reputation: 44316
A 3D camera needs a vector so it knows how to tilt the camera. This is normally the up direction, and is a positive Y vector. If the camera is parallel to the up direction, it has no idea what is up, so it guesses, and you can't tilt the camera. To let the camera tilt, you need to modify the up direction.
I haven't used Three.js, but I think you can use the camera.up vector.
You may also get it to work by limiting angles to 0.1 < x < 179.9
Upvotes: 3