2

I'm using PointerLockControls in Three.js.

On mouse click, I want to update a sphere position to the position the camera is facing, at the same z-position of a certain object. I've read about getDirection(), but can't seem to implement it the right way. Here's what I tried:

var mouse3D = new THREE.Vector3();
mouse3D.normalize();
controls.getDirection( mouse3D );
sphere.position.x = mouse3D.x;
sphere.position.y = mouse3D.y;
sphere.position.z = object.position.z;

The z-position is fine, but x and y are so close to 0 that the sphere stays "on the ground" and doesn't go "left or right".

Any help is much appreciated!

binoculars
  • 2,226
  • 5
  • 33
  • 61

1 Answers1

0

direction is a normalized vector (length is 1)

you have to find factor so that camera.position + direction * factor gives vector with z = object.position.z

factor = (object.position.z - camera.position.z)/direction.z

and just multiply your mouse3D vector mouse3D.multiplyScalar(factor)

Derte Trdelnik
  • 2,656
  • 1
  • 22
  • 26
  • I tried `var factor = (object.position.z - camera.position.z)/mouse3D.z; mouse3D.multiplyScalar(factor);` . This seems to put the sphere at the right x position, but the y position is still off. The sphere always appears beneath of where I clicked... any thoughts? Also, the moment I start moving my character (like in a first person shooter), the x position isn't correct either. – binoculars Jul 08 '16 at 13:28
  • you have to add the camera position to the resulting position `sphere.position = camera.position.clone().add(mouse3D)` – Derte Trdelnik Jul 08 '16 at 15:24
  • Thanks for your reply, but that doesn't seem to fix the issues I mentioned above. – binoculars Jul 08 '16 at 15:33