How to update object position for Raycaster and Intersection

I’m new to Three.js and came so far a long way, only I have this issue which I can’t solve. I’ve this glTF face model which successfully ‘looks’ at the position of the mouse. I got the tracking working on the full window, even outside the canvas (which is needed). Since the canvas will not be full screen.

Now I’ll run into an issue where the face direction doesn’t align with the mouse location. This issue happens when I place the canvas inside a column on the right, the object thinks the canvas is still originated from the top left corner of the window. I’m using this code to track the mouse movement:

var plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), -10);
 var raycaster = new THREE.Raycaster();
 var mouse = new THREE.Vector2();
 var pointOfIntersection = new THREE.Vector3();
 document.addEventListener("mousemove", onMouseMove, false);

function onMouseMove(event) {
   mouse.x = (event.clientX / canvas.clientWidth) * 2 - 1;
   mouse.y = - (event.clientY / canvas.clientHeight) * 2 + 1;
   raycaster.setFromCamera(mouse, camera);
   raycaster.ray.intersectPlane(plane, pointOfIntersection);
   scene.lookAt(pointOfIntersection);
 }

I don’t really know how to approach this problem. How do I update the new object position relative to the screen so the raycaster and pointOfIntersection align the face direction accordingly to it’s position?

Since it’s kinda hard to explain, here a link to my (site) with all the code. You can see the alignment issue when you place the mouse on the nose of the model. It should look face forward instead a slight deviation. - this won’t happen if I place the canvas directly on the left side

Try to compute your mouse coordinates like so:

const rect = renderer.domElement.getBoundingClientRect();
mouse.x = ( ( event.clientX - rect.left ) / ( rect.right - rect.left ) ) * 2 - 1;
mouse.y = - ( ( event.clientY - rect.top ) / ( rect.bottom - rect.top) ) * 2 + 1;

Works like a charm! Thanks Mugen87!

1 Like