Reputation: 431
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.
Upvotes: 4
Views: 11276
Reputation: 251
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.
Upvotes: 13
Reputation: 44336
lookAt
is not available as a vector, it is actually a method in THREE.Object3D
as you can see here. The method is used to create a rotation matrix that is applied to the object to change the rotation (the direction) of the object.
So if you want to know what the current direction (lookAt) of the object is you have to extract this information from the object's rotation.
In local space a camera is looking down the z-axis. If you apply the camera rotation to that vector the result is the lookAt
or direction of the camera.
var vector = new THREE.Vector3( 0, 0, -1 );
vector.applyQuaternion( camera.quaternion );
Check also this answer to a similar question.
Upvotes: 5