【发布时间】:2017-12-28 16:17:42
【问题描述】:
所以我创建了一个“相机控制器”,它创建一个 Object3D 并将其作为相机的父级。 Y 轴的平移和旋转应用于 Object3D,并且 X 轴的旋转应用于相机。 这是代码:
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吗? -
是的,我用的是最新的,我注意到当它还是个孩子的时候,它的局部变换不会改变,所以我不得不想出一个性能低下的解决方案,但它可以工作,我会把它贴在答案上。谢谢你的回复。
-
@sanjileo
this.baseobject.position = this.cam.position;是无效的three.js 代码。见this answer。
标签: javascript matrix three.js camera raycasting