# Need Help adding camera position constraints

Hi, I am trying to set constraints on how far my camera can move on both the x and y axis. I am primarily a 3D content developer with very minimal coding experience. Here is what I have and it works, just need a way to constraints so the camera is bound to a certain area. THANKS!

``````using UnityEngine;
using System.Collections;

public class CameraDrag : MonoBehaviour {

Camera cam;
Vector3 oldPos;
Vector3 pos;
Vector3 deltaPos;

// Use this for initialization
void Start() {
cam = Camera.main;
Debug.Log("start");
}

// Update is called once per frame
void Update() {
if (Input.GetMouseButtonDown(2)) {
Vector3 mousePos = Input.mousePosition;
mousePos.z = 1;

oldPos = cam.ScreenToWorldPoint(mousePos);
}

if (Input.GetMouseButton(2)) {
Vector3 mousePos = Input.mousePosition;
mousePos.z = 1;

pos = cam.ScreenToWorldPoint(mousePos);

deltaPos = new Vector3(oldPos.x - pos.x, oldPos.y - pos.y, oldPos.z - pos.z);
cam.transform.position += deltaPos;
}

if (Input.GetMouseButtonDown(2)) {
oldPos = pos;
}
}
}
``````

Yo can try this:

``````deltaPos = new Vector3(oldPos.x - pos.x, oldPos.y - pos.y, oldPos.z - pos.z);

Vector3 newPos = cam.transform.position + deltaPos;

Vector3 newPosClamped = new Vector3(Mathf.Clamp(newPos.x, minX, maxX), Mathf.Clamp(newPos.y, minY, maxY), Mathf.Clamp(newPos.z, minZ, maxZ));

cam.transform.position = newPosClamped;
``````

I was able to finally figure it out. Here is my completed script. Thanks so much for the help!

``````using UnityEngine;
using System.Collections;

public class CameraDrag : MonoBehaviour {

Camera cam;
Vector3 oldPos;
Vector3 pos;
Vector3 deltaPos;

// Use this for initialization
void Start() {
cam = Camera.main;
Debug.Log("start");
}
public float minX, maxX, minY, maxY, minZ, maxZ;
// Update is called once per frame
void Update() {
if (Input.GetMouseButtonDown(2)) {
Vector3 mousePos = Input.mousePosition;
mousePos.z = 1;

oldPos = cam.ScreenToWorldPoint(mousePos);
}

if (Input.GetMouseButton(2)) {
Vector3 mousePos = Input.mousePosition;
mousePos.z = 1;

pos = cam.ScreenToWorldPoint(mousePos);

deltaPos = new Vector3(oldPos.x - pos.x, oldPos.y - pos.y, oldPos.z - pos.z);

Vector3 newPos = cam.transform.position + deltaPos;

Vector3 newPosClamped = new Vector3(Mathf.Clamp(newPos.x, minX, maxX), Mathf.Clamp(newPos.y, minY, maxY), Mathf.Clamp(newPos.z, minZ, maxZ));

cam.transform.position = newPosClamped;
}

if (Input.GetMouseButtonDown(2)) {
oldPos = pos;
}
}
}
``````