How to limit camera drag with clamp?

HI!

I’m making a 2D game and I want to click and drag to move the camera and I’ve found a script to help me to do that, but, if I drag to far I go outside my game area so I need a way to limit or Clamp the movement of the camera so it only moves to a certain area. Can some one please help?

This is the script I have to work with

 public class dragcam : MonoBehaviour {
    		private Vector3 ResetCamera;
    		private Vector3 Origin;
    		private Vector3 Diference;
    		private bool Drag=false;
    		void Start () {
    			ResetCamera = Camera.main.transform.position;
    		}
    		
    
    		void LateUpdate () {
    			if (Input.GetMouseButton (0)) {
    				Diference=(Camera.main.ScreenToWorldPoint (Input.mousePosition))- Camera.main.transform.position;
    				if (Drag==false){
    					Drag=true;
    					Origin=Camera.main.ScreenToWorldPoint (Input.mousePosition);
    				}
    			} else {
    				Drag=false;
    			}
    		if (Drag==true){
    				Camera.main.transform.position = Origin-Diference;
    			}
    			//RESET CAMERA TO STARTING POSITION WITH RIGHT CLICK
    			if (Input.GetMouseButton (1)) {
    				Camera.main.transform.position=ResetCamera;
    			}
    		}
    }

@codywulfy i’m sure its too late now but hopefully this answer finds someone in need of help. I compiled this from a bunch of different questions and answers and it works great for me. the variables left, right, up, and down set the minX, maxX, minY, and maxY. -10f is my z value for my 2d game so change that to whatever. The format got a bit messed up here but you should be able to figure it out.

using System.Collections;
using System.Collections.Generic;
using System.Numerics;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.UIElements;

public class camScript : MonoBehaviour
{

public float dragSpeed = 2;
private UnityEngine.Vector3 dragOrigin;
public float left = -5;
public float right = 5;
public float down = -5;
public float up = 5;
private void Update()
{

    if (Input.GetMouseButtonDown(0))
    {
        dragOrigin = Input.mousePosition;
        return;
    }

    if (!Input.GetMouseButton(0)) return;

    UnityEngine.Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - dragOrigin);
    UnityEngine.Vector3 move = new UnityEngine.Vector3(pos.x * dragSpeed, pos.y * dragSpeed, -10f);

    transform.Translate(move, Space.World);
    transform.position = new UnityEngine.Vector3(
    Mathf.Clamp(transform.position.x, left, right),
    Mathf.Clamp(transform.position.y, down, up),
    -10f);

}

}

I write a simple and reliable script for my game to handle camera drag and swipe for any aspect ratio. Everyone can use this code easily :slight_smile:

using UnityEngine;

public class CameraDragController : MonoBehaviour
{
    [SerializeField] private Vector2 xBoundWorld;
    [SerializeField] private Vector2 yBoundWorld;
    [SerializeField] public bool HorizentalDrag = true;
    [SerializeField] public bool VerticalDrag = true;
    [SerializeField] public float speedFactor = 10;

    private float leftLimit;
    private float rightLimit;
    private float topLimit;
    private float downLimit;

    public bool allowDrag = true;
    private void Start()
    {
        CalculateLimitsBasedOnAspectRatio();
    }

    public void UpdateBounds(Vector2 xBoundNew, Vector2 yBoundNew)
    {
        xBoundWorld = xBoundNew;
        yBoundWorld = yBoundNew;
        CalculateLimitsBasedOnAspectRatio();
    }

    private void CalculateLimitsBasedOnAspectRatio()
    {
        leftLimit = xBoundWorld.x - Camera.main.ViewportToWorldPoint(new Vector3(0, 0, 0)).x;
        rightLimit = xBoundWorld.y - Camera.main.ViewportToWorldPoint(new Vector3(1, 0, 0)).x;
        downLimit = yBoundWorld.x - Camera.main.ViewportToWorldPoint(new Vector3(0, 0, 0)).y;
        topLimit = yBoundWorld.y - Camera.main.ViewportToWorldPoint(new Vector3(0, 1, 0)).y;
    }

    Vector3 lastPosView; // we use viewport because we don't want devices pixel density affect our swipe speed
    private void LateUpdate()
    {
        if (allowDrag)
        {
            if (Input.GetMouseButtonDown(0))
            {
                lastPosView = Camera.main.ScreenToViewportPoint(Input.mousePosition);
            }
            else if (Input.GetMouseButton(0))
            {
                var newPosView = Camera.main.ScreenToViewportPoint(Input.mousePosition);
                var cameraMovment = (lastPosView - newPosView) * speedFactor;
                lastPosView = newPosView;

                cameraMovment = Limit2Bound(cameraMovment);

                if (HorizentalDrag)
                    Camera.main.transform.Translate(new Vector3(cameraMovment.x, 0, 0));
                if (VerticalDrag)
                    Camera.main.transform.Translate(new Vector3(0, cameraMovment.y, 0));
            }
        }
    }

    private Vector3 Limit2Bound(Vector3 distanceView)
    {
        if (distanceView.x < 0) // Check left limit
        {
            if (Camera.main.transform.position.x + distanceView.x < leftLimit)
            {
                distanceView.x = leftLimit - Camera.main.transform.position.x;
            }
        }
        else // Check right limit
        {
            if (Camera.main.transform.position.x + distanceView.x > rightLimit)
            {
                distanceView.x = rightLimit - Camera.main.transform.position.x;
            }
        }

        if (distanceView.y < 0) // Check down limit
        {
            if (Camera.main.transform.position.y + distanceView.y < downLimit)
            {
                distanceView.y = downLimit - Camera.main.transform.position.y;
            }
        }
        else // Check top limit
        {
            if (Camera.main.transform.position.y + distanceView.y > topLimit)
            {
                distanceView.y = topLimit - Camera.main.transform.position.y;
            }
        }

        return distanceView;
    }
}