Gaming in Unity

08. Unity 2D Game 4 - Camera


In this guide, you will script the Camera to follow SpriteCharacter!

Step 1 - Cinemachine Set-up

Cinemachine is a package that will help us make the camera follow a target in 2D.

Go to the top of the Unity Editor and open Window -> Package Manager.

Find the Cinemachine entry and click on Install in the bottom right-corner.

Once you've installed Cinemachine, create a 2D camera in Hierarchy by clicking Cinemachine at the top and then Create Virtual Camera.


This will create CM vcam1. From now on, Main Camera will copy the properties of this camera.

Drag-and-drop SpriteCharacter from the Hierarchy into the Follow property of vcam1.

Press Play and you'll see that the camera follows SpriteCharacter around!

Step 2 - Confining Camera Boundaries

When you get to the edge of the map, you're able to see outside.

To fix this, we need to add an extension.

Click on vcam1 and then click Add Extension in the Inspector.

Select CinemachineConfiner2D.


The CinemachineConfiner2D needs a Polygon Collider 2D to use as its boundary.

Right-click in the hierarchy and select Create -> Empty. Name the empty GameObject CameraConfiner.

Click Add Component, search for Polygon Collider 2D and add it.

Edit the Collider so that each Point is at the edge of the map.


Currently, this Collider will push our Character out of the map. We need to create a new Layer for the Confiner to ensure it doesn't collide with parts of our game.

Create a new Layer called Confiner and set CameraConfiner's Layer to Confiner.


Go to the top-right of the Editor and then go Edit -> Project Settings.

Go to Physics 2D and scroll down to the bottom, untick all boxes under Confiner.


Click on CM vcam1 and then drag CameraConfiner onto Bounding Shape 2D.


The camera will now follow CharacterSprite without going past the edges of the map.

Created by: David Corish