How to have camera follow player unless it hits a boundary

I’m currently making a top-down 2D game. The way I want the player and camera movement is much like the game undertale. My player can move freely within a set of boundaries. I want my camera to follow the player and keep the player centered to it. But if the camera hits the boundaries and stops moving, I want the player to be able to keep moving up until the boundaries as well even if it means leaving the middle of the camera. I then want the camera to go back to following the player in the center if it’s not hitting any boundaries anymore.

the code I used to follow the player and stay centered was this -

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraControls : MonoBehaviour
{
public GameObject player;
private Vector3 offset = new Vector3(0, 0, -10);

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void LateUpdate()
{
    transform.position = player.transform.position + offset;
}

}

this did a pretty good job, but unfortunately, it neglects the boundaries I have set for the camera in another script in favor of following the player and keeping the player centered in the camera view.

You can detect collisions by using OnCollisionEnter2D(Collision col).

Make sure you have a boolean to tell when you crossed the boundary

When you cross the boundary, set the cameraFollow variable to false.

As you can see, I’ve added an if statement in the LateUpdate() function for you that says whenever cameraFollow is true, the camera will follow the player’s position.

So in OnCollisionEnter2D(), we set it to false because the player passed a boundary.

bool cameraFollow;

void OnCollisionEnter2D(Collision col)
{
    if(col.gameObject.tag == "Boundary")
    {
        cameraFollow = false;
    }
}

void LateUpdate()
{
    if (cameraFollow)
    {
        transform.position = player.transform.position + offset;
    }
}