d_z90
d_z90

Reputation: 1263

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!

Upvotes: 12

Views: 27629

Answers (2)

Max Sherbakov
Max Sherbakov

Reputation: 1955

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.

Upvotes: 2

uhura
uhura

Reputation: 2683

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

Upvotes: 36

Related Questions