Prevent the camera from leaving the terrain

The camera moves behind the Before - this is the GameObject.

public Transform Before, Camera;
public static volatile bool IsMove = false;
private float Speed = 0f;
private void FixedUpdate() {
    Speed = Rb.velocity.magnitude / 0.5f;
    IsMove = 1 > Speed;
    Camera.position = Vector3.Lerp(Camera.position, Before.position, (Speed <= 0 ? 11 : Speed) * Time.fixedDeltaTime);
}

Everything works fine, except that I can't figure out how to calculate that the camera has approached the boundary of the tirrane and there is no need to move it any further?

UPD:
I tried to do it like this:

if (!Physics.Raycast(cam.ViewportPointToRay(new Vector3(1, 0, 0)), cam.farClipPlane, terrainLayer)) {
    camera.position = new Vector3(oldPosition.x, camera.position.y, oldPosition.z);
    print("Right");
} else if (!Physics.Raycast(cam.ViewportPointToRay(new Vector3(0, 1, 0)), cam.farClipPlane, terrainLayer)) {
    camera.position = new Vector3(oldPosition.x, camera.position.y, oldPosition.z);
    print("Left");
}

But it was possible, as you can see, only 2 sides, but with the upper and lower parts, it will not work out in any way.

I need the camera to move the object only if it can be moved.

That is, if we move the object to the right side:

enter image description here

Then we can move along the y axis, if we have not reached the end point y. It needs to work automatically.


A simple idea, do raycast on each corner of the camera with the terrain, if failed, reject the movement.

Camera cam;
Transform camera;
var oldPosition = cameraTransform.position;
cameraTransform.position = newPosition;

int terrainLayer = LayerMask.GetMask("Terrain");

if (!Physics.Raycast(cam.ViewportPointToRay(new Vector3(0, 0, 0)), cam.farClipPlane, terrainLayer))
    camera.position = oldPosition ;
else if (!Physics.Raycast(cam.ViewportPointToRay(new Vector3(0, 1, 0)), cam.farClipPlane, terrainLayer))
    camera.position = oldPosition ;
else if (!Physics.Raycast(cam.ViewportPointToRay(new Vector3(1, 0, 0)), cam.farClipPlane, terrainLayer))
    camera.position = oldPosition ;
else if (!Physics.Raycast(cam.ViewportPointToRay(new Vector3(1, 1, 0)), cam.farClipPlane, terrainLayer))
    camera.position = oldPosition ;