Touch code for panning and zooming not working

I’m using Unity 2017 and working in 2D with an orthographic camera.

The problem is I can’t wrap my head arround whats wrong with my code.


I just want to pan and zoom the camera with touch and only do this when not over an UI element but nothing is working.


If you could help me or point me out where I made a mistake, I would be so thankful.


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

public class CameraController : MonoBehaviour {
	
	Vector2 StartPosition;
	Vector2 DragStartPosition;
	Vector2 DragNewPosition;
	Vector2 Finger0Position;
	float DistanceBetweenFingers;

	public float zoomOutMin = 6;
	public float zoomOutMax = 20;
	
    void Update () {
		checkTouchOnScreen ();
	}

	void checkTouchOnScreen () {

		if (Input.touchCount > 0 && Input.GetTouch(0).phase ==TouchPhase.Began) {
			//Make sure finger is NOT over a UI element
			if (!EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) {
				OnScreenTouched ();
			}
		}
	}

	void OnScreenTouched () {
		Debug.Log ("not over UI");

		if (Input.touchCount == 1) {
			if (Input.GetTouch(0).phase == TouchPhase.Moved) {
				Vector2 NewPosition = GetWorldPosition();
				Vector2 PositionDifference = NewPosition - StartPosition;
				Camera.main.transform.Translate (-PositionDifference);
			}
			StartPosition = GetWorldPosition ();
		} else if (Input.touchCount == 2) {
			if (Input.GetTouch(1).phase == TouchPhase.Moved) {

				DragNewPosition = GetWorldPositionOfFinger(1);
				Vector2 PositionDifference = DragNewPosition - DragStartPosition;

				if (Vector2.Distance (DragNewPosition, Finger0Position) < DistanceBetweenFingers) {
					Camera.main.orthographicSize += (PositionDifference.magnitude);
				}

				if (Vector2.Distance (DragNewPosition, Finger0Position) >= DistanceBetweenFingers) {
					Camera.main.orthographicSize -= (PositionDifference.magnitude);
				}
				DistanceBetweenFingers = Vector2.Distance (DragNewPosition, Finger0Position);
			}
			DragStartPosition = GetWorldPositionOfFinger (1);
			Finger0Position = GetWorldPositionOfFinger (0);
		}
	}

	Vector2 GetWorldPosition () {
		return Camera.main.ScreenToWorldPoint (Input.mousePosition);
	}

	Vector2 GetWorldPositionOfFinger (int FingerIndex) {
		return Camera.main.ScreenToWorldPoint (Input.GetTouch (FingerIndex).position);
	}
}

Your code works just for the moment the touch starts. So you get the first position but no changes.

     void checkTouchOnScreen () {
 
         if (Input.touchCount > 0 && Input.GetTouch(0).phase ==TouchPhase.Began) {

Handle the “TouchPhase.Began” together with the other ones: