坐标系转换
下面函数可以将鼠标所在点的屏幕坐标转化成一个Threejs三维坐标:
convertTo3DCoordinate(clientX,clientY){var mv = new THREE.Vector3((clientX / window.innerWidth) * 2 - 1,-(clientY / window.innerHeight) * 2 + 1,0.5 );mv.unproject(this.camera); //这句将一个向量转成threejs坐标return mv;}
其中:
var mv = new THREE.Vector3((clientX / window.innerWidth) * 2 - 1,-(clientY / window.innerHeight) * 2 + 1,0.5 );
第三个参数是可以改变的,并且改变后获得的threejs坐标的x,y,z数值上会改变,但是差值上不会改变。
研究坐标间关系可用代码:
convertTo3DCoordinate(clientX,clientY){console.log("cx: " + clientX + ", cy: " + clientY);var mv = new THREE.Vector3((clientX / window.innerWidth) * 2 - 1,-(clientY / window.innerHeight) * 2 + 1,0.5 );console.log("mx: " + mv.x + ", my: " + mv.y+", mz:"+mv.z);mv.unproject(this.camera);console.log("x: " + mv.x + ", y: " + mv.y+", z:"+mv.z);return mv;}
让物体跟随鼠标移动的方法
首先在鼠标按下时,计算鼠标的位置在threejs中的坐标,然后将物体的位置设置为鼠标的位置:
function onDocumentMouseMove(event){event.preventDefault();var mouse = convertTo3DCoordinate(event.clientX,event.clientY);group.position.copy(mouse)
}