# Preventing Camera from Leaving the Map Border

I’m making a RTS camera script. I am stuck on a way to keep the camera from moving off the map. The camera is above the map, angled down (currently 45 degrees). Because of that, when viewing the bottom part of the map, the position camera is not over the terrain. The camera’s height is variable as is the angle the camera’s looking down. I am looking for a way to keep the terrain always in the camera’s field of view for variable heights, look angles, and orientations. If anyone can point me in the right direction, it will be much appreciated.

I would set up triggers to the positions where the max up, right left down position of the cam ( on a 2D plane) would go. Then, in whatever script you use to rotate the cam, just limit it.

Thanks for the quick reply. I was hoping for a method that would not require that I hard code camera triggers since that will limit the map size. Is there no other way?

I think what renman3000 meant was that you’d have a gameObject at all 4 corners of the map, and load them into the cam script via inspector. Then, you could tell the camera not move beyond those points by reading their `transform.position` values.

Hope that helps. That’s how I’d do it

I do this from the other end by reading the terrain size values and coding bounds based on those. Then when rotating/moving camera clamping the camera’s transform to those calculated bounds. This script for instance will clamp the camera such that it’s transform can’t go off the map terrain edge.

``````var myTerrain : Terrain; // link from inspector or obtained via GetComponent / Object.Find

//this value is used to further clamp the camera away from the edge.
//Transform will not travel closer than nonPassibleBorderWidth from a terrain edge
var nonPassibleBorderWidth:float = 0;

var mapMinBounds:Vector3;
var mapMaxBounds:Vector3;

function Start()
{
//calculate Terrain bounds
var myTerrainTransform=myTerrain.transform;
mapMinBounds =Vector3(myTerrainTransform.position.x,0,myTerrainTransform.position.z);
mapMaxBounds+=minBounds+Vector3(myTerrain.terrainData.size.x,0,myTerrain.terrainData.size.z);

//apply any border edging spce clamping
mapMinBounds.x+=nonPassibleBorderWidth;
mapMinBounds.z+=nonPassibleBorderWidth;
mapMaxBounds.x-=nonPassibleBorderWidth;
mapMaxBounds.z-=nonPassibleBorderWidth;
}

function Update()
{
//bounds check on camera transform code
if(transform.position.x > maxBounds.x) {
transform.position.x = maxBounds.x;
}
if(transform.position.z > maxBounds.z) {
transform.position.z = maxBounds.z;
}
if(transform.position.x < minBounds.x) {
transform.position.x=minBounds.x;
}
if(transform.position.z < minBounds.z) {
transform.position.z=minBounds.z;
}
}
``````

The above is a really neat solution. Works like a charm but you need to set variables for min and maxBounds. Probably goes without saying but… yeah.

Does it for angled camera? this code works just when camera is perpendicular to the terrain.