About

  1. Use this script if you want to achieve pinch zoom-in and zoom-out effect in unity.     Note : This is compatible with Orthographic Camera only for the time being.
    In the next update I will include its working for the Perspective Camera also.
  2. Pinching in/out will increase/decrease the orthographic size of the camera respectively.

How to use this script:

  1. Attach this script to an empty game object.
  2. Now run the code on any  device.  

Code :

using UnityEngine;
using System.Collections;

public class PinchTestOne : MonoBehaviour {

	// It sets the size of the camera at runtime.
        // after the fingers pinch in/out.
	float distance;
	// The max scale limit of the camera .
	public float maxScale = 20f;
	// The min scale limit of the camera .
	public float minScale = 7f;

	// Use this for initialization
	void Start () {
		//Set the main camera's size to minScale.
		Camera.main.orthographicSize = minScale;
	}

	// Update is called once per frame
	void Update () {
		//If two fingers are touched on the display.
		if(Input.touchCount==2){
			//Store the first and second touch
			Touch touch0 = Input.GetTouch(0);
			Touch touch1 = Input.GetTouch(1);

	//the current distance between the two fingers touched on the screen
			Vector3 currentDist = touch0.position - touch1.position;
	//Calculate the previous distance when the fingers were moved
			Vector3 prevDist = (touch0.position - touch0.deltaPosition) - (touch1.position-touch1.deltaPosition);

	//The magnitude of two vectors is to be calculated which gives a very large value. Dividing by an integer triggers the smoothness of the changing value of the delta.
			float delta = (currentDist.magnitude - prevDist.magnitude)/50;

			//decreases the distance with factor.
			distance-=delta;
			//limit the maximum and the minimum values
			if(distance<minScale){
				distance = minScale;
			}
			if(distance>maxScale){
				distance = maxScale;
			}

			// Change the size of the camera accordingly with pinch
			// which turns out to be a pinch/zoom effect
			Camera.main.orthographicSize = distance;
		}

	}
}

Note :

  1. Since this script’s variables are not accessible by any other GameObjects, hence class functions and variables are not mentioned here separately
  2. However, the uses of the variables/function in the code are properly commented.

 

Post By:- Siddharth Verma