Perspective Camera PanningHow To Pan Around A Scene in Unity

Author Waldo
Published November 17, 2018

In this tutorial I explain how to write a C# script that will allow you to pan around the screen for a mobile or touch screen device in a perspective or 3D environment.

Video Walkthrough

  • 1:00 - Understanding How Panning Works
  • 1:15 - Setting up the Panning Script
  • 2:05 - Difference between Perspective and Orthographic Cameras
  • 2:35 - Creating the function to plot our points using Raycast
  • 5:10 - Finished Example
  • 5:30 - Finished Example using SimpleTown Asset Store Package

​Source Code for PerspectivePan.cs

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

public class PerspectivePan : MonoBehaviour {
    private Vector3 touchStart;
    public Camera cam;
    public float groundZ = 0;

	// Update is called once per frame
	void Update () {
        if (Input.GetMouseButtonDown(0)){
            touchStart = GetWorldPosition(groundZ);
        }
        if (Input.GetMouseButton(0)){
            Vector3 direction = touchStart - GetWorldPosition(groundZ);
            cam.transform.position += direction;
        }
    }
    private Vector3 GetWorldPosition(float z){
        Ray mousePos = cam.ScreenPointToRay(Input.mousePosition);
        Plane ground = new Plane(Vector3.forward, new Vector3(0,0,z));
        float distance;
        ground.Raycast(mousePos, out distance);
        return mousePos.GetPoint(distance);
    }
}

 

Resources

  1. Orthographic Pan & Zoom Tutorial
  2. Simple Town Asset Store Package

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

Discussion

Browse Tutorials About