ThreeJs Object轻松观察鼠标 [英] ThreeJs Object look at mouse with ease

查看:233
本文介绍了ThreeJs Object轻松观察鼠标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使一个物体以自然的方式一直看着鼠标。到目前为止,我已经设法

I'm trying to make an object keep looking at the mouse in a natural-ish way. So far, i've managed to


  • 使对象始终保持鼠标状态

  • 添加放松以使
    更加自然

问题在于,现在的对象不遵循相同的路径作为鼠标,但始终将其放到最后一个位置。

The problem is now that the object doesn't follow the same path as the mouse but always takes the last position to ease to.

我不确定该如何处理。

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

所以现在的目标是找到一种使对象跟随鼠标的方法,不仅是最后一个位置,还包括它的整个路径。有想法吗?

So the goal is now to find a way to make the object follow the mouse, but not only the last position, its whole path. Any ideas?

推荐答案

您可以使用类似的模式使对象以延迟缓和的方式看着鼠标:

You can make an object look at the mouse with delayed easing by using a pattern like so:

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

}

编辑:这是一个使用稍有不同实现的实时演示: https://threejs.org/examples/webgl_materials_skin.html

Here is a live demo using a slightly different implementation: https://threejs.org/examples/webgl_materials_skin.html.

three.js r.99

three.js r.99

这篇关于ThreeJs Object轻松观察鼠标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆