Reputation:
I have a problem : I have a cube and I want it to go where I want (forward, backward, left or right). The problem is when I rotate the camera, the "forward" direction must be in front of it everytime, same for others directions.
In fact I already got it to work with forward and backward by doing this :
// For forward
camera.getWorldDirection( direction )
cube.position.add(direction)
// For backward
camera.getWorldDirection( direction )
cube.position.sub(direction)
My real question is how I do to "rotate" the vector direction at 90° so I just have to add and sub to the cube position to go left and right ?
Upvotes: 0
Views: 360
Reputation: 104783
You want to specify a direction in camera space and convert that direction to world space. You can do so by following a pattern like this one:
// create once and reuse
var RightDir = new THREE.Vector3( 1, 0, 0 );
var UpDir = new THREE.Vector3( 0, 1, 0 );
var ForwardDir = new THREE.Vector3( 0, 0, - 1 ); // the camera looks down its negative-z axis
var dir = new THREE.Vector3();
var distance = 10;
Then, to move the cube to the right, for example:
dir.copy( RightDir ).transformDirection( camera.matrixWorld ).multiplyScalar( distance );
cube.position.add( dir );
To move to the left, use a negative distance.
Note: camera.matrixWorld
is typically updated for you by the renderer. If in your app it is not, then you need to call camera.updateMatrixWorld()
before you access it.
three.js. r.85
Upvotes: 2