Pan & ZoomHow to Pan and Zoom on Touch Devices in Unity

Author Waldo
Published July 12, 2018

In this tutorial I explain how to write a C# script that will allow you to pinch to zoom and pan around the screen for a mobile or touch screen device.

Video Walkthrough

  • 1:00 How to build a script to pan around the screen
  • 3:07 How to zoom using the mouse's scroll wheel
  • 5:13 How to zoom using the pinch technique

Source Code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PanZoom : MonoBehaviour {
    Vector3 touchStart;
    public float zoomOutMin = 1;
    public float zoomOutMax = 8;
	// Update is called once per frame
	void Update () {
            touchStart = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        if(Input.touchCount == 2){
            Touch touchZero = Input.GetTouch(0);
            Touch touchOne = Input.GetTouch(1);

            Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
            Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;

            float prevMagnitude = (touchZeroPrevPos - touchOnePrevPos).magnitude;
            float currentMagnitude = (touchZero.position - touchOne.position).magnitude;

            float difference = currentMagnitude - prevMagnitude;

            zoom(difference * 0.01f);
        }else if(Input.GetMouseButton(0)){
            Vector3 direction = touchStart - Camera.main.ScreenToWorldPoint(Input.mousePosition);
            Camera.main.transform.position += direction;
        zoom(Input.GetAxis("Mouse ScrollWheel"));

    void zoom(float increment){
        Camera.main.orthographicSize = Mathf.Clamp(Camera.main.orthographicSize - increment, zoomOutMin, zoomOutMax);

This tutorial is sponsored by this community

In order to stick to our mission of keeping education free, our videos and the content of this website rely on the support of this community. If you have found value in anything we provide, and if you are able to, please consider contributing to our Patreon. If you can’t afford to financially support us, please be sure to like, comment and share our content — it is equally as important.

Join The Community


Browse Tutorials About