Skip to content

Implement Camera Pan and Zoom Controls in Unity2D

Implement Camera Pan and Zoom Controls in Unity2D

In this tutorial, we will learn to implement camera pan and zoom controls in Unity2D.

We sometimes require independent camera controls in many 2D applications, where the camera is not attached to the main character. These applications include RTS games, Simulation games, GIS specific applications and many more. This tutorial will implement a camera pan and zoom controls in Unity2D.

Contact me

Find the GitHub repository of this tutorial at https://github.com/shamim-akhtar/camera-manipulator-2d.

The WebGL Version

The Unity Project

  • Create a new Unity 2D project.
  • Right click on the project hierarchy and create an empty game object. Name it Map
  • Select the Assets foldera and create a new folder named Resources, and then create another folder named Images in the Resources folder.
  • Download the Sentosa_1.jpg and put it in the Images folder. Drag and drop this Sentosa_1 sprite into the Map game object
The picture shows the Sentosa map.

The Canvas and Minimal UI

We aim to implement the pan and zoom function of the camera. The zoom in and zoom out will happen within minimum and maximum values. We will use a slider for zoom in and zoom out.

So, let’s go ahead and create a minimal UI to demonstrate the functionalities of the pan and zoom of our camera for this demonstration.

  • Right-click on the project hierarchy and create a Canvas. Set the canvas properties as shown below.
The canvas properties
  • Right-click on the Canvas and add a UI Panel. Call it SliderPanel. Set the properties of the SliderPanel as shown below. You can set the transparency to 100% if you wish (in the color field below).
Properties of the Slider Panel
  • Select the SliderPanel and add a UI Slider. We will use this slider for zoom in and zoom out controls. Set the properties of the slider as shown below.
Properties of the Slider

The Camera Manipulator

Select the camera and add a new script component called CameraManipulator2D. Double-click CameraManipulator2D and open in Visual Studio.

The Variables

  • SerializeField variables.
  // Set the min and the max size for this 
  // camera so that we can fix the limits
  // of our zoom in and zoom out.
  [SerializeField]
  float CameraSizeMin = 1.0f;
  [SerializeField]
  float CameraSizeMax = 10.0f;
  // The slider for zoom-in and zoom-out
  [SerializeField]
  public Slider SliderZoom;
Code language: C# (cs)
  • Private variables.
  // Some variables needed for dragging our 
  // camera to creae the pan control
  private Vector3 mDragPos;
  private Vector3 mOriginalPosition;
  private bool mDragging = false;
  // The zoom factor
  private float mZoomFactor = 0.0f;
  // Save a reference to the Camera.main
  private Camera mCamera;
Code language: C# (cs)

Add a property to enable/disable our camera panning. Sometimes you might want to disable camera panning. For example, when you are dragging or interacting with a game object. In such a situation, you want to disable camera panning to enable dragging of that game object.

  // A property to allow/disallow 
  // panning of camera.
  // You can set panning to be false
  // if you want to disable panning.
  // One exmaple could be when you are
  // dragung or interacting with a game object 
  // then you can disable camera panning.
  public static bool IsCameraPanning
  {
    get;
    set;
  } = true;Code language: C# (cs)

The Start Method

  void Start()
  {
    if(CameraSizeMax < CameraSizeMin)
    {
      float tmp = CameraSizeMax;
      CameraSizeMax = CameraSizeMin;
      CameraSizeMin = tmp;
    }
    if(CameraSizeMax - CameraSizeMin < 0.01f)
    {
      CameraSizeMax += 0.1f;
    }
    SetCamera(Camera.main);
  }
  public void SetCamera(Camera camera)
  {
    mCamera = camera;
    mOriginalPosition = mCamera.transform.position;
    // For this demo, we simple take the current camera
    // and calculate the zoom factor.
    // Alternately, you may want to set the zoom factor
    // in other ways. For example, randomize the 
    // zoom factory between 0 and 1.
    mZoomFactor = 
      (CameraSizeMax - mCamera.orthographicSize) / 
      (CameraSizeMax - CameraSizeMin);
    if (SliderZoom)
    {
      SliderZoom.value = mZoomFactor;
    }
  }
Code language: C# (cs)

Zoom Related Methods

  public void Zoom(float value)
  {
    mZoomFactor = value;
    // clamp the value between 0 and 1.
    mZoomFactor = Mathf.Clamp01(mZoomFactor);
    if(SliderZoom)
    {
      // if the slider is valied
      // set the value to the slider.
      SliderZoom.value = mZoomFactor;
    }
    // set the camera size
    mCamera.orthographicSize = CameraSizeMax -
        mZoomFactor * 
        (CameraSizeMax - CameraSizeMin);
  }
  public void ZoomIn()
  {
    // For this demo we hardcode 
    // the increment. You should
    // avoid hardcoding the value.
    Zoom(mZoomFactor + 0.01f);
  }
  public void ZoomOut()
  {
    Zoom(mZoomFactor - 0.01f);
  }
Code language: C# (cs)

The Update Method for Dragging/Panning

  void Update()
  {
    // Camera panning is disabled when a tile is selected.
    if (!IsCameraPanning)
    {
      mDragging = false;
      return;
    }
    // We also check if the pointer is not on UI item
    // or is disabled.
    if (EventSystem.current.IsPointerOverGameObject() || 
      enabled == false)
    {
      //mDragging = false;
      return;
    }
    // Save the position in worldspace.
    if (Input.GetMouseButtonDown(0))
    {
      mDragPos = mCamera.ScreenToWorldPoint(
        Input.mousePosition);
      mDragging = true;
    }
    if (Input.GetMouseButton(0) && mDragging)
    {
      Vector3 diff = mDragPos - 
        mCamera.ScreenToWorldPoint(
          Input.mousePosition);
      diff.z = 0.0f;
      mCamera.transform.position += diff;
    }
    if (Input.GetMouseButtonUp(0))
    {
      mDragging = false;
    }
  }Code language: JavaScript (javascript)

The Slider Function

  public void OnSliderValueChanged()
  {
    Zoom(SliderZoom.value);
  }Code language: JavaScript (javascript)

Now, go to Unity Editor and associate the Slider’s OnValueChanged field with the CameraManipulator2D’s OnSliderValueChanged.

Associate the slider’s OnValueChanged field

Click Play and run the application. You should see it as below.

The GitHub version of the source code also contains three buttons. One for zoom-in, zoom-out and reset camera view.

Read My Other Tutorials

  1. Implement Drag and Drop Item in Unity
  2. Graph-Based Pathfinding Using C# in Unity
  3. 2D Grid-Based Pathfinding Using C# and Unity
  4. 8-Puzzle Problem Using A* in C# and Unity
  5. Create a Jigsaw Puzzle Game in Unity
  6. Implement a Generic Pathfinder in Unity using C#
  7. Create a Jigsaw Puzzle Game in Unity
  8. Generic Finite State Machine Using C#
  9. Implement Bezier Curve using C# in Unity
  10. Create a Jigsaw Tile from an Existing Image
  11. Create a Jigsaw Board from an Existing Image
  12. Solving 8 puzzle problem using A* star search
  13. A Configurable Third-Person Camera in Unity
  14. Player Controls With Finite State Machine Using C# in Unity
  15. Finite State Machine Using C# Delegates in Unity
  16. Enemy Behaviour With Finite State Machine Using C# Delegates in Unity
  17. Augmented Reality – Fire Effect using Vuforia and Unity
  18. Implementing a Finite State Machine Using C# in Unity
  19. Solving 8 puzzle problem using A* star search in C++
  20. What Are C# Delegates And How To Use Them
  21. How to Generate Mazes Using Depth-First Algorithm

3 thoughts on “Implement Camera Pan and Zoom Controls in Unity2D”

  1. I have to thank you for the efforts you’ve put in penning this blog.
    I really hope to see the same high-grade blog posts
    by you later on as well.

Leave a Reply

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