javascript - ThreeJs Object 轻松看鼠标
问题描述
我试图让一个物体以一种自然的方式一直看着鼠标。到目前为止,我已经设法
- 让对象一直看着鼠标
- 添加缓动以使更自然
现在的问题是对象不遵循与鼠标相同的路径,而是始终位于最后一个位置以缓和到。
我不知道如何解决这个问题。
// create object and add to scene
const sphere = new THREE.Mesh( geometry, material );
const origin = new THREE.Vector3(0, 0, 75);
sphere.position.x = 0;
sphere.position.z = 0;
sphere.lookAt(origin);
scene.add( sphere );
window.addEventListener("mousemove", onmousemove, false);
var plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var intersectPoint = new THREE.Vector3();
function onmousemove(event) {
var startRotation = sphere.quaternion.clone();
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
raycaster.ray.intersectPlane(plane, intersectPoint);
intersectPoint.z = 75; // so that the object is still always facing the camera which has a position.z of 75 too
sphere.lookAt(intersectPoint);
var endRotation = sphere.quaternion.clone();
sphere.quaternion.copy( startRotation );
createjs.Tween.get(sphere.quaternion).to(endRotation, 1000, createjs.Ease.getPowOut(2.2));
marker.position.copy(intersectPoint);
}
所以现在的目标是找到一种方法让对象跟随鼠标,但不仅仅是最后一个位置,它的整个路径。有任何想法吗?
解决方案
您可以使用以下模式使对象以延迟缓动的方式注视鼠标:
var target = new THREE.Vector3();
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
...
function onDocumentMouseMove( event ) {
mouseX = ( event.clientX - windowHalfX );
mouseY = ( event.clientY - windowHalfY );
}
function animate() {
requestAnimationFrame( animate );
target.x += ( mouseX - target.x ) * .02;
target.y += ( - mouseY - target.y ) * .02;
target.z = camera.position.z; // assuming the camera is located at ( 0, 0, z );
object.lookAt( target );
renderer.render( scene, camera );
}
三.js r.131
推荐阅读
- jmeter - 为什么 Jmeter 吞吐量整形计时器允许的请求比配置的多?
- javascript - 为什么一个 Promise 会返回一个对象 Promise,即使我明确地放了 `return`?
- reactjs - 使用 React、Webpack 和 Apache 启用文本压缩
- silverstripe - SilverStripe 4.1 - SS_DEFAULT_ADMIN_USERNAME 和 PASSWORD 不受尊重
- javascript - 如何抓取存储在 html 页面中的图像
- ios - 在视图控制器之间平移(不滑动)
- javascript - 检查项目的离子存储
- node.js - 使用硒获取最后一个 Whats 应用程序的问题
- ios - 使用 UIImage 滚动时表视图单元格滞后
- javascript - 断言超时和等待方法有什么区别