I have an object in my scene and want to get the normalized vector that represents the direction it is facing. In Unity, the equivalent is transform.forward. How can I access this in THREE.js?
Here is how to determine the direction vector in which an object is facing, or "looking":
By default, an object is considered to be looking up its internal positive z-axis, so create a vector pointing in the direction of the positive z-axis:
var vector = new THREE.Vector3( 0, 0, 1 );
Now, apply the same rotation to the vector that is applied to the object:
vector.applyQuaternion( object.quaternion );
The resulting vector will be pointing in the direction that the object is facing -- as long as the object has no transformed parent objects.
If the object has a parent that has a transform applied, then instead of using object.quaternion
, you need to compute the object's "world quaternion", and use that instead. You do that like so:
var position = new THREE.Vector3();
var scale = new THREE.Vector3();
var quaternion = new THREE.Quaternion();
var vector = new THREE.Vector3( 0, 0, 1 );
. . .
object.updateMatrixWorld(); // the renderer does this for you each render loop, so you may not have to
object.matrixWorld.decompose( position, quaternion, scale );
vector.applyQuaternion( quaternion );
If the "object" is a camera, then see this answer: three.js set and read camera look vector.
three.js r.68
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With