I am creating a sphere in Three.js
which has to follow the mouse whenever it moves, as displayed in this example. The function that handles the mouse movement is the following:
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
mouseMesh.position.set(event.clientX, event.clientY, 0);
};
I attach a JSFiddle with the complete code inside it, where you can see that according to the DOM, mouseMesh
is undefined. Do you have an idea of what am I doing wrong?
Thanks in advance for your replies!
For sphere to follow mouse, you need to convert screen coordinates to threejs world position. Reference link.
Updated fiddle
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 ) );
You should use a THREE.Raycaster for this. When you set a list of intersectObjects you will be able to get an array of objects that intersected with the ray. So you can get the position from the 'clicked' object from returned list
Basically, you need to project from the 3D world space and the 2D screen space. Renderers use projectVector for translating 3D points to the 2D screen. unprojectVector is basically for doing the inverse, unprojecting 2D points into the 3D world. For both methods you pass the camera you're viewing the scene through. So, in this code you're creating a normalised vector in 2D space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With