Working with 2D cameras

If you've been following the previous tutorials, you now have a 2D scene with a default, stationary, NavCam.

A default 2D Camera, created in the Scene Manager, looks like this:

Notice how the Camera component above it is inactive. This is because it is used for reference only - the MainCamera uses this camera's values to perform the actual rendering.

Adjust the Camera's Size value so that we can see enough of the scene, but still have room to move. With the 2D Demo's background sprites, a value of around 2.3 is enough.

If you do not see the Camera Preview in the Scene window, make sure that the Camera component is expanded.

If your Camera Preview looks stretched, be sure to set your game's aspect ratio to something fixed. Go to the Game window and change the Free Aspect property to your desired ratio.

Since we can see enough of the scene vertically, we only need to vary our camera's horizontal position as the Player walks around the scene. In the GameCamera2D Inspector, uncheck the Horizontal movement panel's Lock? checkbox. Some new options will appear:

The default values will cause the camera to follow the Player. However, if the Player moves too far to one side of the scene, the edges of the background sprites will become visible, because the camera will always be centering in on the Player.

If you have yet to create a 2D Player to test your game with, you can use the Brain2D prefab in AdventureCreator → 2D Demo → Resources. Drag this prefab into your scene to make him the scene's active Player

Back to our camera, we can assign constraints to limit how far in the X-direction it can move, to prevent our scene edges from being visible. First, check the Constrain? checkbox, to show more fields beneath it:

We can either set the values manually in the Minimum and Maximum values directly, or assign our main background object into the Background constraint field. Doing this will ensure that the camera never leaves the background's boundary - even if the resolution or aspect ratio changes:

Whenever our Player is closer to the scene's centre, notice how the camera will always try to place him in the screen's centre. To make things a little less rigid, we can increase the Track freedom value. A value of 0.1 will mean that the camera will only move if the Player has moved close to the screen's edge.

Finally, we can also adjust the camera's Follow speed, from within the Target object to control camera movement panel, which becomes visible when either one of the camera's move directions are unlocked.