Three.js - Object follows mouse position

I create a sphere in Three.js, which should follow the mouse whenever it moves, as shown in this example . The function that handles mouse movement is as follows:

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 am attaching a JSFiddle with the full code inside it, where you can see that according to the DOM, is undefined. Do you have any idea what I'm doing wrong? mouseMesh

Thanks in advance for your answers!

+3
source share
2 answers

In order for the sphere to follow the mouse, you need to convert the screen coordinates to the threejs world position. Link Link .

​​

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 ) );
+15

THREE.Raycaster. intersectObjects, , . , "clicked"

, 3D- 2D-. Renderers projectVector 3D- 2D-. unprojectVector , 2D- 3D-. , . , 2D-.

+1

All Articles