Make camera follow the character to an extent

Hi,

I got a basic script for my camera, which is simply tracking the character like this:

var xposition : float;
var yposition : float;
var player : Transform;

function Update () {
	transform.position = Vector3(player.position.x + xposition, player.position.y + yposition, -20);
}

The problem is that if the character is jumping too high, as in outside the background limit of the game on the y-axis, the camera will obviously follow it outside aswell.

Is there a way to make the camera always stay within some kind of box limit, to prevent it from moving too high? And then follow the character again once it is inside that limit?

Yes there is, in the transform.position line we simply need to clamp the x and y values. Now this isn’t as simple as it seems since what the camera see is not what the transform position is. You can use Camera.WorldToScreenPoint to help with this detection. Basically once you know what the biggest/smallest x value should be for the transform we can clamp it.

transform.position = Vector3(Mathf.Clamp(player.position.x + xposition, -10, 10) ..)

That will return a value at most 10 and at least -10