Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
288 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...