本文介绍了Three.js - 对象跟随鼠标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在 Three.js
中创建一个球体,它在鼠标移动时必须跟随鼠标,如 这个例子.处理鼠标移动的函数如下:
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);
};
我附上了一个 JSFiddle 里面有完整的代码,你可以看到根据 DOM,mouseMesh
是未定义的.你知道我做错了什么吗?
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?
提前感谢您的回复!
推荐答案
为了让球体跟随鼠标,需要将屏幕坐标转换为threejs世界位置.参考链接.
For sphere to follow mouse, you need to convert screen coordinates to threejs world position. Reference 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 ) );
这篇关于Three.js - 对象跟随鼠标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!