首页 > 解决方案 > 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);
}

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

标签: javascriptthree.js3d

解决方案


您可以使用以下模式使对象以延迟缓动的方式注视鼠标:

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


推荐阅读