将当前屏幕上的坐标转换成3d中的坐标
pos 是当前canvas屏幕上的坐标,targetZ 是物体距离原点的距离private get3DPosByCanvasPos (pos: THREE.Vector2, targetZ: number) { let vec = new THREE.Vector3(); // create once and reuselet target = new THREE.Vector3(); // create once and reusevec.set(( pos.x / window.innerWidth ) * 2 - 1,- ( pos.y / window.innerHeight ) * 2 + 1,0.5 );let camera = this.camera;vec.unproject( camera );vec.sub( camera.position ).normalize();
var distance = (targetZ - camera.position.z) / vec.z;
target.copy( camera.position ).add( vec.multiplyScalar( distance ) );return target;}
如果想让创建的模型以右边界靠近屏幕可以使用
let vec2 = new THREE.Vector2(window.innerWidth, window.innerHeight / 2);let pos = Game3DMgr.i.get3DPosByCanvasPos(vec2, 0.2);// 这里计算了物体所在三维空间的大小// 将计算玩的左边减去所占最大和大小值的一般就是 物体当前体积的一般。this.puteBoundingBox();let halfWidth = (this.basketBg.geometry.boundingBox.max.x - this.basketBg.geometry.boundingBox.min.x) / 2;pos.x -= halfWidth;this.basketBg.position.set(pos.x, pos.y, pos.z);