Three.js - 对象跟随鼠标位置

d_z*_*z90 6 javascript three.js

我正在创建一个球体,Three.js每当它移动时必须跟随鼠标,如本例所示.处理鼠标移动的功能如下:

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);
};
Run Code Online (Sandbox Code Playgroud)

我附上一个JSFiddle,其中包含完整的代码,根据DOM,你可以看到它mouseMesh是未定义的.你知道我做错了什么吗?

提前感谢您的回复!

uhu*_*ura 25

要使球体跟随鼠标,您需要将屏幕坐标转换为threejs世界位置.参考链接.

更新了小提琴

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 ) );
Run Code Online (Sandbox Code Playgroud)