How to keep a RTS Style Camera, with Rotation, in bounds.

I’ve just spent the last 10 hours trying to write a suitable camera controller script for a game I am making and am getting rather frustrated. I need to make a camera stay in the bounds of the map. But simply staying in bounds is easy; I need it to not even be able to view the edge of the map. This causes a problem because I have the camera rotated slightly, and even when the camera is withing the bounds of the map it can see beyond it.

I have tried many different solutions today, but none of them seem quite right. This is my latest attempt, but it still won’t work. This one stops at the edge of the map, but then (for some reason) wont let me pull back from the edge.

I need a camera controller that will prevent a slightly rotated camera from ever seeing the edge of the map.

var myTerrain : Terrain;
var cameraBox : GameObject; // An invisible box that surrounds the camera

var scrollArea = 7; // Defines the distance from the edge of the window that scrolling starts
var scrollSpeed = 27;
var dragSpeed = 1;


function moveMe(myDir : Vector3) {
	[COLOR="#696969"]// If the following movement would take the camera out of bounds ( predicted by vector
	// position of the edge + vector of the translation) prevent the movement.[/COLOR]
	var viewPosRB : Vector3 = camera.WorldToViewportPoint ((new Vector3(myTerrain.transform.position.x + myTerrain.terrainData.size.x,  myTerrain.transform.position.y, myTerrain.transform.position.z)) + (myDir * scrollSpeed * Time.deltaTime));
	if ((viewPosRB.x < 1) || (viewPosRB.y > 0)) {return;}

	var viewPosLT : Vector3 = camera.WorldToViewportPoint ((new Vector3(myTerrain.transform.position.x, myTerrain.transform.position.y,  myTerrain.transform.position.z + myTerrain.terrainData.size.z )) + (myDir * scrollSpeed * Time.deltaTime));
	if ((viewPosLT.x > 0) || (viewPosLT.y < 1)) {return;}

	cameraBox.transform.Translate(myDir * scrollSpeed * Time.deltaTime);
}


function Update () {							
	moveMe(Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")));
}

Anyone have any ideas? I’m still stuck on this.

the reason you get stuck is that you move slightly out of bounds, and then you do not allow for more movement? The easist solution to a problem like this is to have a bigger map than allowed to view. So when the player reaches the edge with the camera he sees a part of a map his troops are not allowed to be, (intead of a big blue nothing or whatever skybox you are using). So in the IF , test if he is outside bounds, and then set the camera to one step inside so that camera does not get stuck.