Perspective Camera PanningHow To Pan Around A Scene in Unity

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.

In this video:

  • 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

 

Resources

  1. Orthographic Pan & Zoom Tutorial
  2. Simple Town 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);
    }
}

LINK TO THIS POST

SHARE THIS POST


DISCUSSION