Skip to content
Advertisement

Raycaster do not stays in center when i am updating camera

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(); 
}

”’

Advertisement

Answer

You should take a look at the Raycaster.setFromCamera() docs. It says right there the first argument is a Vector2 with mouse coordinates in the [-1, 1] range. Since you want the center of the screen, make it 0 on the X and 0 on the Y axes:

// Setting mousePosition to (0, 0) makes it the center of your screen 
var mousePos = new THREE.Vector2(0, 0);
raycaster.setFromCamera(mousePos, camera);

intersects = raycaster.intersectObjects(scene.children);
if(intersects.length > 0){
    console.log(intersects[0]);
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement