Unity 3D Game Engine – Android – Multi Touch – Pich to Zoom – JavaScript

ZommIn ZoomOut the camera using pinch gesture.

Inside Hierarchy create:

1. Cube (Gameobject)

2. Main Camera, attach the script ‘PinchZoom.js’

PinchZoom.js:


#pragma strict

// Pinch to Zoom
// Attach this script to Main Camera

public var perspectiveZoomSpeed : float = 0.5f;  // The rate of change of the field of view in perspective mode. E' la velocità con la quale si avrà lo zoom
public var orthoZoomSpeed : float = 0.5f;        // The rate of change of the orthographic size in orthographic mode.  E' la velocità con la quale si avrà lo zoom


function Update()
{
    // If there are two touches on the device...
    if (Input.touchCount == 2)
    {
        // Store both touches.
        var touchZero = Input.GetTouch(0);
        var touchOne = Input.GetTouch(1);

        // Find the position in the previous frame of each touch.
        var touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
        var touchOnePrevPos = touchOne.position - touchOne.deltaPosition;

        // Find the magnitude of the vector (the distance) between the touches in each frame.
        var prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
        var touchDeltaMag = (touchZero.position - touchOne.position).magnitude;

        // Find the difference in the distances between each frame.
        var deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;

        // If the camera is orthographic...
        if (camera.isOrthoGraphic)
        {
            // ... change the orthographic size based on the change in distance between the touches.
            camera.orthographicSize += deltaMagnitudeDiff * orthoZoomSpeed;

            // Make sure the orthographic size never drops below zero.
            camera.orthographicSize = Mathf.Max(camera.orthographicSize, 0.1f);
        }
        else
        {
            // Otherwise change the field of view based on the change in distance between the touches.
            camera.fieldOfView += deltaMagnitudeDiff * perspectiveZoomSpeed;

            // Clamp the field of view to make sure it's between 0 and 180.
            // Clam in inglese significa 'morsetto', significa limitare il valore ad un valore massimo ed un valore minimo prestabilito
            camera.fieldOfView = Mathf.Clamp(camera.fieldOfView, 0.1f, 179.9f);
        }
    }
}