Unity 5 2D Camera Bounds

I need help making camera boundaries for my 2D game. I want the camera to stop when it hits the edge of the level, but start following the player again if he moves the other way into the level again. I’m pretty new to C# so I don’t really know how I’m going to do this. Any ideas?

Here is the scripts that tells the camera to follow the player:

using UnityEngine;
using System.Collections;

public class FollowPlayer : MonoBehaviour {
	
	public PlayerController player;
	
	public bool isFollowing;
	
	public float xOffset;
	public float yOffset;

	// Use this for initialization
	void Start () {
		player = FindObjectOfType<PlayerController> ();
		
		isFollowing = true;
	}

	// Update is called once per frame
	void Update () {
		if(isFollowing) {
			transform.position = new Vector3(player.transform.position.x + xOffset, player.transform.position.y + yOffset, transform.position.z);
		}
	}
}

I’ve also tried to set isFollowing to false every time the player hits a certain trigger, but whenever the player went back into the level, the camera just jumped to the player, which didn’t look very good.

I'm wondering... why don't you make the camera a child of the player (in the hierarchy), so that it moves together with the player, without the need for a FollowPlayer script? Is there a reason for that? I mean, all that your code does, is to move the camera, so that it's always at a fixed position in relation to the player. The same would be achieved if the camera is a child of the player. Am I missing something?

@Gooball60 pako has suggested one of the simplest way but still if you dont want to make the camera child of player you can clamp the position of the camera to restrict its movement in space http://docs.unity3d.com/ScriptReference/Mathf.Clamp.html

Well, in that case you need to clamp the position of the camera between the left and right boundaries. So, MadDevil's comment should help you out.

1 Answer

1

@Gooball60

pako has suggested one of the simplest way but still if you dont want to make the camera child of player you can clamp the position of the camera to restrict its movement in space