Device Pinch Detection C# for Unity

Here’s a clever way to detect pinching either in or out on a mobile device in Unity.

//if touchCount (fingers) is equal to two that means we have two fingers on screen
  if ( iPhoneInput.touchCount == 2 )
   {
//setup our fingers to track
      var touch1 : iPhoneTouch = iPhoneInput.GetTouch( 0 );
      var touch2 : iPhoneTouch = iPhoneInput.GetTouch( 1 );

       //if our positions are reducing - zoom out camera 
      //NOTE: you can replace this code to do whatever you want with it
      if ( touch1.position.x < touch2.position.x )
         Camera.main.transform.position.z -= ( touch1.positionDelta.x - touch2.positionDelta.x ) / 10;

     //if our positions are increasing - zoom in camera 
      if ( touch1.position.x > touch2.position.x )
         Camera.main.transform.position.z += ( touch1.positionDelta.x - touch2.positionDelta.x ) / 10;
       
      if ( touch1.position.y < touch2.position.y )
         Camera.main.transform.position.z -= ( touch1.positionDelta.y - touch2.positionDelta.y ) / 10;
      if ( touch1.position.y > touch2.position.y )
         Camera.main.transform.position.z += ( touch1.positionDelta.y - touch2.positionDelta.y ) / 10;
 
       
      if ( Camera.main.transform.position.z > -2 )
         Camera.main.transform.position.z = -2;
      if ( Camera.main.transform.position.z < -15 )
         Camera.main.transform.position.z = -15;
 
   }

You can apply this in an update method. :smile:

2 Likes