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 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 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.
- 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).
- 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.
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.
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
- Implement Drag and Drop Item in Unity
- Graph-Based Pathfinding Using C# in Unity
- 2D Grid-Based Pathfinding Using C# and Unity
- 8-Puzzle Problem Using A* in C# and Unity
- Create a Jigsaw Puzzle Game in Unity
- Implement a Generic Pathfinder in Unity using C#
- Create a Jigsaw Puzzle Game in Unity
- Generic Finite State Machine Using C#
- Implement Bezier Curve using C# in Unity
- Create a Jigsaw Tile from an Existing Image
- Create a Jigsaw Board from an Existing Image
- Solving 8 puzzle problem using A* star search
- A Configurable Third-Person Camera in Unity
- Player Controls With Finite State Machine Using C# in Unity
- Finite State Machine Using C# Delegates in Unity
- Enemy Behaviour With Finite State Machine Using C# Delegates in Unity
- Augmented Reality – Fire Effect using Vuforia and Unity
- Implementing a Finite State Machine Using C# in Unity
- Solving 8 puzzle problem using A* star search in C++
- What Are C# Delegates And How To Use Them
- How to Generate Mazes Using Depth-First Algorithm
A committed and optimistic professional who brings passion and enthusiasm to help motivate, guide and mentor young students into their transition to the Industry and reshape their careers for a fulfilling future. The past is something that you cannot undo. The future is something that you can build.
I enjoy coding, developing games and writing tutorials. Visit my GitHub to see the projects I am working on right now.
Educator | Developer | Mentor
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.
Thank you for this tutorial.
A simple yet great tutorial. I like the simplicity with which you write your tutorials. Thank you.