0
0
Unityframework~5 mins

2D camera setup in Unity

Choose your learning style9 modes available
Introduction

A 2D camera in Unity lets you control what part of your game world the player sees. It helps focus on the important action and creates a smooth experience.

When you want to show only a part of a large 2D game world to the player.
When you want the camera to follow the player character as they move.
When you want to zoom in or out to show more or less of the scene.
When you want to create effects like shaking the screen during explosions.
When you want to set up a fixed view for menus or cutscenes.
Syntax
Unity
Camera.main.orthographic = true;
Camera.main.orthographicSize = 5f;
Camera.main.transform.position = new Vector3(x, y, z);

Use orthographic = true to make the camera 2D (no perspective).

orthographicSize controls how much of the scene is visible vertically.

Examples
Sets the main camera to 2D mode with a default zoom size.
Unity
Camera.main.orthographic = true;
Camera.main.orthographicSize = 5f;
Moves the camera to follow the player, keeping the camera 10 units behind on the z-axis.
Unity
Camera.main.transform.position = new Vector3(player.transform.position.x, player.transform.position.y, -10f);
Changes the zoom level by adjusting the orthographic size.
Unity
Camera.main.orthographicSize = 3f; // Zoom in
Camera.main.orthographicSize = 10f; // Zoom out
Sample Program

This script sets the camera to 2D mode and smoothly follows the player with a fixed offset behind on the z-axis.

Unity
using UnityEngine;

public class CameraFollow2D : MonoBehaviour
{
    public Transform player;
    public float smoothSpeed = 0.125f;
    public Vector3 offset = new Vector3(0, 0, -10);

    void Start()
    {
        Camera.main.orthographic = true;
        Camera.main.orthographicSize = 5f;
    }

    void LateUpdate()
    {
        Vector3 desiredPosition = player.position + offset;
        Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
        transform.position = smoothedPosition;
    }
}
OutputSuccess
Important Notes

Always keep the camera's z-position negative in 2D so it can see the scene.

Use LateUpdate() to move the camera after the player moves for smooth following.

Adjust orthographicSize to control zoom level; smaller means zoomed in.

Summary

Set the camera to orthographic mode for 2D games.

Use the camera's position to control what part of the scene is visible.

Follow the player smoothly by updating the camera position each frame.