There was an error when using the raycaster to determine whether the target was blocked

Q1:There was an error when using the raycaster to determine whether the target was blocked.

Expect:Verify that the occlusion logic is correct

Explain:

code:

function checkTargetIsVisiable(targetModel, visibleModel) {
	
    if (!targetModel || !visibleModel || !raycaster) {
        return false;
    }

	const targetMeshlist = getMeshesUsingTraverse(targetModel);
	const visibleMeshlist = getMeshesUsingTraverse(visibleModel);

    if (targetMeshlist.length === 0 || visibleMeshlist.length === 0) {
        return false;
    }

    const targetBBox = new THREE.Box3().expandByObject(targetModel);
    const targetCenter = targetBBox.getCenter(new THREE.Vector3());
    
	//const lookat = controls.target;
	const lookat = targetCenter.clone();

    const direction = lookat.clone().sub(camera.position);
	 if (direction.lengthSq() < 0.0001) { 
        return true;
    }
	direction.normalize();
    raycaster.set(camera.position, direction);
    try {
        const intersects = raycaster.intersectObjects(
            visibleMeshlist.filter(obj => obj instanceof THREE.Object3D), 
            true
        );
		let firstIntersectsMesh = null;
        for (let i = 0; i < intersects.length; i++) {
            const intersect = intersects[i];
            if (intersect.object && intersect.object.isMesh) {
                firstIntersectsMesh = intersect.object;
                break; 
            }
        }

        if (!firstIntersectsMesh) {
            return false;
        }

        const isTargetVisible = targetMeshlist.some(mesh => mesh === firstIntersectsMesh);
        console.log(isTargetVisible ? 'visible' : 'invisible');
        return isTargetVisible;
	} catch(error){
        return false; 
	}
   
}

These types of bugs are best tracked down by debugging. You may start top to bottom inspecting the value of each variable and you had to find where things break. Or you can go bottom up starting from wrong answer and looking back why it happens.

By just looking at the source, only one thing comes to mind - you raycast against the visible meshes, so if there are hits, they are for objects in the visibles. But the final result you check whether the intersection is a member of the targets. This could possibly return true only if you raycast through an object that belongs to both groups - visibles and targets. I have no idea what do these group contain and whether targets are part of visible.

Would this also work for you case if you simplify the check - you cast a ray to your target and get the closest object (hit at index 0). If it belongs to the target, then assume the target is visible.

2 Likes