Nicolas Oñate
Nicolas Oñate

Reputation: 221

mouse movent event not same coords

I have a 3d animation who i want to detect colitions with mouse, i try to follow with a ball and this ball is not same position than mouse.

Working example in codepen

This function is a copy paste of this other answer but it dont work for me.

// Follows the mouse event
function onMouseMove(event) {

    // Update the mouse variable
    event.preventDefault();
    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;

    // Make the sphere follow the mouse
    var vector = new THREE.Vector3(mouse.x, mouse.y, 0.5);
    vector.unproject(camera);
    var dir = vector.sub(camera.position).normalize();
    var distance = - camera.position.z / dir.z;
    var pos = camera.position.clone().add(dir.multiplyScalar(distance));
    sphereInter.position.copy(pos);

    // Make the sphere follow the mouse
    sphereInter.position.set(event.clientX, event.clientY, 0);
}

As you can see, the blue ball is not same place than mouse, how can i fix it?

Upvotes: 2

Views: 37

Answers (1)

Mugen87
Mugen87

Reputation: 31086

I suggest you add the mousemove event listener to renderer.domElement instead of document and then use this code for computing the components of mouse:

const rect = renderer.domElement.getBoundingClientRect();

mouse.x = ( ( event.clientX - rect.left ) / rect.width ) * 2 - 1;
mouse.y = - ( ( event.clientY - rect.top ) / rect.height ) * 2 + 1;

Upvotes: 2

Related Questions