I'm working on a 3D animation and trying to detect collisions with the mouse. I've attempted to make a ball follow the mouse, but it's not aligning correctly.
Here's a working example in CodePen
This function is borrowed from another answer on Stack Overflow, but it's not functioning as expected 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 in the same place as the mouse. How can I correct this issue?