Pan a 3D orthographic camera within bounds

Currently working on a system that allows the player to pan the camera around the world with their mouse. Only issue is that I don’t know how to keep the player from panning so far they leave the map.

Any ideas that don’t make me have to rewrite the entire script?

NOTE: This is for a mobile game, so I’m looking for something like how Clash of Clans limits it’s panning to just the village.

Here’s my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraPanAndZoom : MonoBehaviour
{
    Vector3 touchStart;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            touchStart = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        }
        if (Input.GetMouseButton(0))
        {
            Vector3 direction = touchStart - Camera.main.ScreenToWorldPoint(Input.mousePosition);
            Camera.main.transform.position += direction;

        }
    }
}

@LoveScapeStudios - you can simply add a few lines of code to your existing script. This method involves checking whether the new camera position would be within the defined bounds before applying the movement.

First, let’s define the boundaries by adding public variables for minX, maxX, minY, and maxY to your CameraPanAndZoom class. Then, we’ll modify the Update() method to check if the new position is within the bounds before moving the camera.

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

public class CameraPanAndZoom : MonoBehaviour
{
    Vector3 touchStart;
    public float minX, maxX, minY, maxY;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            touchStart = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        }
        if (Input.GetMouseButton(0))
        {
            Vector3 direction = touchStart - Camera.main.ScreenToWorldPoint(Input.mousePosition);
            Vector3 newPosition = Camera.main.transform.position + direction;

            newPosition.x = Mathf.Clamp(newPosition.x, minX, maxX);
            newPosition.y = Mathf.Clamp(newPosition.y, minY, maxY);
            newPosition.z = Camera.main.transform.position.z;

            Camera.main.transform.position = newPosition;
        }
    }
}

Now you just need to adjust the minX, maxX, minY, and maxY variables in the Unity Inspector to set the camera boundaries to match your game world.