I have a 3D animation in which I want to detect collisions between objects, for this I have generated a ball that makes contact with the other objects, but it is not in the same position as the mouse.
This is the conflicting function copied from here but it hasn't worked 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 sphere does not move to the same position as the mouse
How can I solve that?
You have to add the event
mousemove
torenderer.domElement
insidedocument
and then use this code to calculate the components ofmouse
: