0

我知道有很多答案如何将鼠标坐标转换为 Three.js 世界坐标(我更喜欢这个)。但是我在使用 TrackballControls 时计算时遇到了麻烦。

首先我期望做的是:我想为我的场景添加一个缩放功能。不是通过鼠标滚轮,用户应该能够绘制一个矩形,并且通过抬起鼠标按钮,相机正在这个矩形上进行缩放。

我已经实现了所有并且它可以工作,但只有当用户没有使用 TrackballControls 旋转/缩放/平移时!如果相机被操纵,我绘制的矩形坐标错误。我真的不知道为什么......我只知道这是 TrackballControls 的问题,因为没有它们,它可以工作。

以前有没有其他人遇到过这个问题?有错误还是我的代码有错误?

var onZoomPlaneMouseDown = function(event){
    event.preventDefault();
    var plane = document.getElementById("zoomPlane");
    var innerPlane = document.getElementById("innerZoomPlane");
    var mouseButton = event.keyCode || event.which;

    mouse.x = ( event.clientX / WIDTH ) * 2 - 1;
    mouse.y = - ( event.clientY / HEIGHT ) * 2 + 1;

    if(mouseButton === 1){ 
        var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
        projector.unprojectVector( vector, camera );
        var dir = vector.sub( camera.position ).normalize();
        var distance = - camera.position.z / dir.z;
        zoomPlaneUpperCorner = camera.position.clone().add( dir.multiplyScalar( distance ) );

        innerPlane.style.display = "block";
        innerPlane.style.top = event.clientY + "px";
        innerPlane.style.left = event.clientX + "px";

    }

    if(mouseButton === 3){ 
        plane.style.display = "none";
        innerPlane.style.display = "none";
    }
};

var onZoomPlaneMouseUp = function(event){
    event.preventDefault();
    var plane = document.getElementById("zoomPlane");
    var innerPlane = document.getElementById("innerZoomPlane");
    var mouseButton = event.keyCode || event.which;

    mouse.x = ( event.clientX / WIDTH ) * 2 - 1;
    mouse.y = - ( event.clientY / HEIGHT ) * 2 + 1;

    var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
    projector.unprojectVector( vector, camera );
    var dir = vector.sub( camera.position ).normalize();
    var distance = - camera.position.z / dir.z;
    zoomPlaneLowerCorner = camera.position.clone().add( dir.multiplyScalar( distance ) );

    if(mouseButton === 1){ 
        plane.style.display = "none";
        innerPlane.style.display = "none";

        var center = new THREE.Vector3();
        center.subVectors(zoomPlaneLowerCorner, zoomPlaneUpperCorner);
        center.multiplyScalar( 0.5 );
        center.add(zoomPlaneUpperCorner);   

        var rayDir = new THREE.Vector3();
            rayDir.subVectors(center, camera.position ).normalize();

        controls.target = center;               

        var height = zoomPlaneUpperCorner.y - zoomPlaneLowerCorner.y;
        var distanceToCenter = camera.position.distanceTo(center);
        var minDist = (height / 2) / (Math.tan((camera.fov/2)*Math.PI/180));

        camera.translateOnAxis(rayDir, (distanceToCenter - minDist));
    }
};
4

0 回答 0