Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three.js - Find the current LookAt of a camera?

I need to read (extract) the current lookAt of a camera in the scene. I have seen the following post but I could not get the lookAt from camera.

three.js set and read camera look vector

Thank you for your help.

like image 668
mbehnaam Avatar asked Sep 12 '25 12:09

mbehnaam


1 Answers

This answer from Wilt is very insightful, but not completely correct. The code returns a vector that points in the same direction that the camera is pointing at. That's a great start!

But unless the camera is at the origin (0, 0, 0) (or lies exactly on the line segment that connects the origin to the rotated vector point without passing beyond that point so that the point is behind the camera) the camera won't be looking at that point. Clearly -- just common sense -- the position of the camera also influences what points are being looked at. Just think about it. The camera method lookAt() looks at a point in 3D space regardless of where the camera is. So to get a point that the camera is looking at you need to adjust for the camera position by calling:

vec.add( camera.position );

It is also worth mentioning that the camera is looking not at a single point but is looking down a line of an infinite number of points, each at a different distance from the camera. The above code from Wilt returns a vector that is exactly one unit in length because the application of a quaternion to the normalized z-axis vector (0, 0, -1) returns another normalized vector (in a different direction). To calculate the look at point at an arbitrary distance x from the camera use:

(new THREE.Vector3( 0, 0, -x )).applyQuaternion( camera.quaternion ).add( camera.position );

This takes a point along the z-axis at a distance x from the origin, rotates it to the direction of the camera and then creates a "world point" by adding the camera's position. We want a "world point" (and not a "relative to the camera point") since camera.lookAt() also takes a "world point" as a parameter.

like image 196
chorpita Avatar answered Sep 14 '25 02:09

chorpita