Linecast not working properly for camera

I was making a 3d camera rotation+zoom script plus the autozoom if the camera hits something so that it doesn’t go through objects and terrain. Everything worked properly except the autozoom which I did with linecast. Here is a part of the script:

void Update()
        x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
            y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

            y = ClampAngle(y, yMinLimit, yMaxLimit);

            Quaternion rotation = Quaternion.Euler(y, x, 0);

        distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel") * 5, distanceMin, distanceMax);

        if (Physics.Linecast(Player.transform.position, MainCamera.transform.position, out hit))
                distance = hit.distance;
        Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
        Vector3 position = rotation * negDistance + Player.transform.position;

        MainCamera.transform.rotation = rotation;
        MainCamera.transform.position = position;

`` For some reason the “if” is never true whatever I do and whatever I place between the camera and the player. And the camera still always goes through. However if I Debug.DrawLine between the camera and the player, the ray clearly goes through these objects. The player has rigidbody and box collider applied to it.
How do I fix this? Many thanks!

Same problem that you that I resolve by doing that

LayerMask terrainLayer; //in variable

//Change your terrain layer in inspector with the name Terrain

//Initialize the layer and Add the layer at the end of this line

terrainLayer = LayerMask.GetMask(“Terrain”);

if (Physics.Linecast(target.position, transform.position, out hit, terrainLayer))

that’s all, not any auto zoom