Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three.js - Object follows mouse position

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!

like image 790
d_z90 Avatar asked Mar 16 '16 11:03

d_z90


2 Answers

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 ) );
like image 130
uhura Avatar answered Dec 11 '22 18:12

uhura


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.

like image 35
Max Sherbakov Avatar answered Dec 11 '22 16:12

Max Sherbakov