因此,我创建了一个“相机控制器”,它创建Object3D并将其作为相机的父项。 Y轴的平移和旋转适用于Object3D,并且 X轴的旋转适用于相机。 这是代码:Three.Js Raycasting在更改相机转换时无法正常工作,因为它是Object3D的子项
function cameracontroll(cam,scene){
this.cam=cam;
this.scene=scene;
this.baseobject=new THREE.Object3D();
//a vector3 that hold the rotations to be applyed
this.rot=new point(0,0,0);
//rotation speed
this.rspeed=0.002;
//move speed
this.mspeed=0.2;
//last mouse X position
this.lx=0;
//last mouse Y position
this.ly=0;
//direction indicators
this.go_up=false;
this.go_down=false;
this.go_left=false;
this.go_right=false;
this.go_forward=false;
this.go_backward=false;
//to correctly initialize mouse position
this.counthelper=0;
//init function
this.init=function(){
this.baseobject.position=this.cam.position;
this.baseobject.add(cam);
this.scene.add(this.baseobject);
}
//rotation updating
this.updaterotation = function(e){
if(this.counthelper==0){this.lx=e.clientX;this.ly=e.clientY;this.counthelper++;}
this.rot.x= ((e.clientX-this.lx)*this.rspeed)*-1;
this.rot.z= ((e.clientY-this.ly)*this.rspeed)*-1;
cam.rotateX(this.rot.z);
this.baseobject.rotateY(this.rot.x);
this.lx=e.clientX;
this.ly=e.clientY;
}
//position updating
this.updateposition = function(){
if(this.goup){
this.baseobject.translateY(this.mspeed);
}
if(this.godown){
this.baseobject.translateY(-this.mspeed);
}
if(this.goleft){
this.baseobject.translateX(this.mspeed);
}
if(this.goright){
this.baseobject.translateX(-this.mspeed);
}
if(this.goforward){
this.baseobject.translateZ(this.mspeed);
}
if(this.gobackward){
this.baseobject.translateZ(-this.mspeed);
}
this.cam.updateMatrix();
}
};
问题是,当我用这个控制器移动摄像机和他的父母 光线投射不再检测网格。
这是光线投影功能
document.addEventListener('click',function(event){
event.preventDefault();
mouse.x = (event.clientX/renderer.domElement.clientWidth) * 2 - 1;
mouse.y = - (event.clientY/renderer.domElement.clientHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(scene.children);
if (intersects.length > 0) {
console.log("Intersects!");
}
},false);
我已经试过“cam.updateMatrix()”和“cam.updateProjectionMatrix”但没有了Object3D我有位置的摄像头成为孩子前后发生了改变。即便初始化它仍然是相同的(0,10,-4)。 任何人都有一个想法,为什么在使用此控制器更改摄像头位置时,光线投射不起作用。
通过使相机成为另一个物体的子物体,其局部变换矩阵永远不会改变(这就是为什么位置仍然相同)。但是,'setFromCamera'使用相机的世界矩阵,根据父对象的方向(r86),它应该有所不同。你使用的是最新版本的three.js吗? – TheJim01
是的,我使用最新的一个,我注意到一个相机,当它是一个孩子,其本地转换不会改变,所以我不得不想出一个可能是低执行的解决方案,但它的工作原理,我会张贴在回答。谢谢你的回复。 – sanjileo
@sanjileo'this.baseobject.position = this.cam.position;'是无效的three.js代码。见[这个答案](https://stackoverflow.com/questions/26905929/three-js-2xmeshes-using-same-vector-as-position/26916159#26916159)。 – WestLangley