ThreeJs Object 轻松查看鼠标 [英] ThreeJs Object look at mouse with ease

查看:21
本文介绍了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.

我不知道如何解决这个问题.

I'm not sure how to approach this.

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

}

three.js r.131

three.js r.131

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

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