three.js set and read camera look vector

前端 未结 4 1659
执笔经年
执笔经年 2020-11-28 11:36

Instead of rotating the camera with camera.rotation or with the lookAt() function I\'d like to pass a look vector directly to the camera... Is it possible to set a camera lo

4条回答
  •  生来不讨喜
    2020-11-28 12:05

    These other answers are 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 code from the other answers 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:

    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 just a "relative to the camera point") since camera.lookAt() also takes a "world point" as a parameter.

提交回复
热议问题