3D模型遵循mousecursor three.js

时间:2018-12-21 18:17:26

标签: javascript three.js mouseevent 3d-model

我最近发现了three.js库,现在已经在尝试它了几天。我想向项目中添加一个鼠标事件,实际上与该示例完全相同,鼠标后面的骷髅头,只是我只想使用我的JSON 3D模型(而在示例中模型的眼睛和下巴动画来模拟咬人

这是示例的链接: https://codepen.io/interaktiv-ca/pen/XayZPx

在此示例中,我尝试了几次以在项目中实现它,但始终得出负面结果。

我的基本设置如下:

var scene = new THREE.Scene();

var camera = new THREE.PerspectiveCamera ( 50, window.innerWidth / window.innerHeight, 1, 1000 );

camera.position.z = 15;

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight);

document.body.appendChild ( renderer.domElement );

controls = new THREE.OrbitControls ( camera, renderer.domElement );

var loader = new THREE.ObjectLoader();
loader.load("/model/skull.json",function ( obj ) {
    var box = new THREE.Box3().setFromObject ( obj );
    var center = new THREE.Vector3();
    box.getCenter( center );
    obj.position.sub ( center );
    obj.rotation.y = Math.PI;
    scene.add ( obj );
});

var animate = function () {
    requestAnimationFrame( animate );
    
    renderer.render( scene, camera );
}

animate();

1 个答案:

答案 0 :(得分:0)

您必须定义raycaster才能知道对象的新位置。您可以在下面使用我的示例代码

onMouseMove(event) {
    const that = this;
    const mouse = this.mouse;
    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
    raycaster.setFromCamera(mouse, this.camera);
    const objectListSelect = [];
    objectListSelect.push(this.plane); // your object will moving around this plane
    const intersects = raycaster.intersectObjects(objectListSelect);
   const item = intersects[i];
     yourobject.position.copy(item.point);

  }