Hello, guys i have a problem with Raycasting and i couldn’t find solution so far.
What i am trying to archieve is that, i want Raycaster to stay always in center, like when i move my camera and look other direction i want Raycaster to stay in center and update please help me.
I am using FirstPersonControls, This is the code i have with raycasting
var raycaster = new THREE.Raycaster();
var arrow = new THREE.ArrowHelper( raycaster.ray.direction, raycaster.ray.origin, 100, Math.random() * 0xffffff );
scene.add( arrow );
var intersects;
function sec(){
requestAnimationFrame(sec);
var directionVector = new THREE.Vector3();
var positionVector = new THREE.Vector3();
var b = camera.getWorldDirection(directionVector);
var c = camera.getWorldPosition(positionVector);
raycaster.setFromCamera( b,camera );
arrow.position.copy(camera.position);
arrow.setDirection(raycaster.ray.direction);
intersects = raycaster.intersectObjects( scene.children );
if(intersects.length>0){
intersects[0].object.material.color.set( 0xff0000 );
}
else if(intersects.length<1 && casted){
for(var i=0; i<arr.length; i++){
arr[i].material.color.set( 0x8f8f8f );
}
}
camera.updateProjectionMatrix();
camera.updateMatrixWorld();
}
The first parameter of setFromCamera() is supposed to be mouse coordinate 2D vector which is not true in your app. Try to use this code instead:
raycaster.set( positionVector, directionVector );
Besides, it’s not necessary to recompute the projection matrix per animation step unless you change camera properties like near, far or fov. Also declare directionVector and positionVector outside of your animation loop and reuse both objects. The variables b and c are not necessary, too.