Trying to implement enemy Field of view .

The enemy can spot the player but i want to add a crouch mechanic to the player that when he crouches behind an obstacle the enemy can’t spot him .


bool FindPlayerTarget()
    {
//searching for player in the surronding area
        Collider[] targetsInViewRadius = Physics.OverlapSphere(transform.position, ViewRadius, PlayerMask);
        if (targetsInViewRadius.Length > 0)
        {
            player = targetsInViewRadius[0];
            Transform target = player.transform;
//getting the direction from enemy to player
            Vector3 dirToTarget = (target.position - transform.position).normalized;
//getting the destination between the two
            float dstToTarget = Vector3.Distance(transform.position, target.position);
// if the player is inside the angle of view of the enemy and within the range 
            if (Vector3.Angle(transform.forward, dirToTarget) < ViewAngle / 2 && dstToTarget < ViewRadius)
            {
// ray cast from enemy to player (the reason i added the vector3 is i want the ray to come out of enemy's eye)
                if (!Physics.Raycast(transform.position + new Vector3(0f, 3.5f, 0f), dirToTarget, dstToTarget, obstacleMask))
                {
// was just debugging
                    Debug.DrawRay(transform.position + new Vector3(0f, 3.5f, 0f), dirToTarget, Color.green);
//player is in sight 
                    return true;
                }
                else
                    return false;
            }
            else return false;
        }
        else return false;
    }

here’s the crouch function from another script
void Update () {
if(Input.GetButtonDown(“Crouch”))
{
IsCrouch = !IsCrouch;
CrouchFunction();
}
}

     void CrouchFunction()
     {
         if(IsCrouch == true)
         {//if player standing then scale is the normal scale of player which is (2,2,2)
             t_mesh.localScale = new Vector3(2, 2, 2);
             ccr_controller.height = 2;
         }
         else
         {
//if not standing i reduce the scale and the height of the collider 
             t_mesh.localScale = new Vector3(1, 1, 1);
             ccr_controller.height = 1f;
         }
     }

the problem is whenever the player is crouched behind an obstacle , the enemy can spot him very well .
i need help please !

old but if you are casting a ray/rays from the enemy to the player and the fist hit is not the player (assuming the ray or rays cover the desired field of view; the crouch should not matter at all. If the any of the rays hit the player as the first hit in the ray cast, you are not hidden else you are hidden.

You could just make an exception to the raycast, so that when the enemy spots the player and the crouching boolean is set to true the enemy cannot spot the player.

psuedo

if(!other.gameObject.getcomponent<script>().isCrouching){
return true;

}