0

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 ?

1 Answer 1

2

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

1
  • Please remember to accept answers when users help you. Commented Aug 27, 2017 at 18:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.