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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#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);
        }
    }
}