Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the normalized vector of the direction an object3D is facing?

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?

like image 984
user1477699 Avatar asked Jan 10 '23 01:01

user1477699


1 Answers

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

like image 167
WestLangley Avatar answered Jan 12 '23 14:01

WestLangley