因此,我創建了一個「相機控制器」,它創建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