Cloudy Water Games

Bounded Multiple Target Camera in Unity

While in the process of designing a platformer/brawler prototype, I needed a camera that would pan and zoom to keep multiple characters in view, a la Super Smash Bros. A lot of this code comes straight from this wonderful blog post, which details how to get a camera to pan and zoom to keep multiple targets in view. However, I also wanted to lock the camera into a certain area. It’s a simple modification, but requires a few important changes to the base code, as well as some additions. Here’s the code I ended up using:


Whoof! That’s a block of code all right. Let’s break that down function by function and see what I changed from the original. First off, I added a public BoxCollider2D. This is the boundary that you don’t want the camera to exit, set up in the Unity Inspector.

 I added a bunch of code to LateUpdate (), too. The If (mCamera.orthographicSize > mLevelBounds.bounds.extents.y) statement considers whether the camera’s size is larger than the bounding box of the level. If it is, we simply set the Camera’s orthographic size to the size of the level. I also added some dampening to the camera movement to smooth it out a bit. The next set of If statements concern whether the camera is showing anything outside of the level bounds, and if it is I move the camera’s position so that it isn’t.

The only changes in CalculateBoundingBox() and CalculateCameraPosition() are where I’m grabbing the target’s positions from. Let’s move on, then.

CalculateOrthographicSize() is what gave me a little trouble at first. The way it’s calculated in the original was causing me trouble since I was locking the camera inside the level bounds. It uses the bounding box’s and camera.WorldToViewportPoint (). I decided to simplify. Instead, I just use whichever value of the bounding box is larger to determine what the orthographic size should be.

Here’s a .gif of it in action in my prototype:

View post on

Leave a Reply

Your email address will not be published. Required fields are marked *