用鼠标在threejs场景中移动对象

Move an object in a threejs scene with mouse

本文关键字:移动 对象 鼠标 threejs      更新时间:2023-09-26

我需要在threejs场景中移动一个对象,但当我用鼠标点击时,我无法选择一个对象。我试着修改这个代码(https://github.com/mrdoob/three.js/blob/master/examples/webgl_interactive_draggablecubes.html)为我的申请,但它在我的情况下不起作用。

这个功能是正确的吗?

摄像头的位置和旋转是否正确(请参阅完整的代码)?

function onDocumentMouseDown(event) {
    console.log("function onDocumentMouseDown");
    console.log(mouse.x, mouse.y);
    raycaster.setFromCamera( mouse, camera );
    var intersects = raycaster.intersectObjects( objetos );
    if (intersects.length > 0) {
        alert("finalmente");
        console.log(intersects[0]);
        intersects[0].object.material.transparent = true;
        intersects[0].object.material.opacity = 0.1;
        SELECTED = intersects[0].object;
        var intersects = raycaster.intersectObject( plane );
        if ( intersects.length > 0 ) {
             offset.copy( intersects[ 0 ].point ).sub(plane.position);
        }
    }
}

对于完整的代码访问https://github.com/lohmanndouglas/Simulador.git

这个问题是因为我在页面中使用了其他div,所以要纠正这个问题,需要将clientX和clientY转换为div的相对坐标。

我更改了更新变量mouse.x和mouse.y的行。

    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

为此:

   mouse.x = ( (event.clientX - event.target.getBoundingClientRect().left) /event.currentTarget.width ) * 2 - 1;
   mouse.y = - ( (event.clientY - event.target.getBoundingClientRect().top) / event.currentTarget.height ) * 2 + 1;

这适用于我