ThreeJs Object look at mouse with ease

2019-07-23 23:54发布

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

  • make the object look at the mouse at all times
  • add an easing to make in more natural

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?

1条回答
smile是对你的礼貌
2楼-- · 2019-07-24 00:17

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

}

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

three.js r.99

查看更多
登录 后发表回答