我知道有很多答案如何将鼠标坐标转换为Three.js世界坐标(我优先this一个)。但是在使用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));
}
};