How to set boundaries with camera movement

Hello,

This is my camera movement :

``````void Update () {
var movement = Vector3.zero;

if (Input.GetKey("a"))
movement.x--;
if (Input.GetKey("d"))
movement.x++;
transform.Translate(movement * speed * Time.deltaTime, Space.Self);

}
``````

I know I can limit it by using Matf.Clamp, but I don’t understand how to implement it.
Tried different implementation and all without success.

Thanks

Have you tried

``````transform.Translate(movement * speed * Time.deltaTime, Space.Self);
transform.position = new Vector3(
Mathf.Clamp(transform.position.x, MIN_X, MAX_X),
Mathf.Clamp(transform.position.y, MIN_Y, MAX_Y),
Mathf.Clamp(transform.position.z, MIN_Z, MAX_Z));
``````

Where `MIN_X`, `MAX_X`, `MIN_Y`, `MAX_Y`, `MIN_Z`, and `MAX_Z` are your min and max values, in world space.

Hello, i’v tried the script above`var cam : GameObject;

void Start() {

cam = GameObject.Find(“Main Camera”);

}

void Update() {
var movement = Vector3.zero;

`````` if ((Input.GetKey("a")) && (cam.transform.x > -10) && (cam.transform.x < 10))
{
movement.x--;
}

if ((Input.GetKey("d")) && (cam.transform.x > -10) && (cam.transform.x < 10))
{
movement.x++;
}

transform.Translate(movement * speed * Time.deltaTime, Space.Self);
``````

}`
and it work as i need but the problem is when a limit is reached the script stops and camera doesn’t move again to the opposite direction

If you want to clamp/restrict gameobjects on the boundary of Minimap, here are the links

Step by step tutorial: http://techscenarios.com/unity3d-clamp-objects-on-edges-of-minimap-clamp-on-minimap-boundary-free-scripts-part-4/

maybe try something like this:

``````var cam : GameObject;

void Start() {

cam = GameObject.Find("Main Camera");

}

void Update() {
var movement = Vector3.zero;

if ((Input.GetKey("a")) && (cam.transform.x > -10) && (cam.transform.x < 10))
{
movement.x--;
}

if ((Input.GetKey("d")) && (cam.transform.x > -10) && (cam.transform.x < 10))
{
movement.x++;
}

transform.Translate(movement * speed * Time.deltaTime, Space.Self);

}
``````

Hope this helps.