Home > Software engineering >  Detect if fingers are pinching in or out
Detect if fingers are pinching in or out

Time:01-05

I am using touch input to do a pinch function. The pinching works but I would like to detect if the two fingers are pinching in (coming closer to each other) or pinching out (moving farther from each other). How does one do this?

I have already tried storing the current ratio to previous ratio in order to check in the next iteration but it fluctuates since I am storing it at every frame. Also, what if the user never lifts off his fingers, how does that work then?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.EnhancedTouch;
using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch;
 
public class DetectTouch: MonoBehaviour {
 
//Touch
    int prevtouchCount;
    float firstDistance;
    float originalZoom;
    float currentZoom;
    float distance;
 
    float ratio;
    float previousRatio;
 
    void Update () {
 
        //Touch
        if (Touch.activeFingers.Count == 2) {
 
            Touch touch1 = Touch.activeFingers[0].currentTouch;
            Touch touch2 = Touch.activeFingers[1].currentTouch;
 
            distance = Vector2.Distance (touch1.screenPosition, touch2.screenPosition);
 
            if (prevtouchCount != 2) {
                firstDistance = distance;
                originalZoom = Camera.main.fieldOfView;
            }
 
            ratio = distance / firstDistance;
 
            if (ratio < previousRatio) {
                Debug.Log("NOT PINCHING");
                previousRatio = ratio;
               
            } else {
                Debug.Log("PINCHING");
                previousRatio = ratio;
               
            }
 
        }
 
    }
}

CodePudding user response:

For the overall resulting pinch direction it would be simply

if(ratio < 1f)
{
    Debug.Log("pinch in");
}
else if(ratio > 1f)
{
    Debug.Log("pinch out");
}

Or you go directly by the distance and do

if(distance > firstDistance)
{
    Debug.Log("pinch in");
}
else if(distance < firstDistance)
{
    Debug.Log("pinch out");
}

If you rather wanted it frame-wise regardless of the overall result I think you should actually be fine doing

if(ratio > previousRatio)
{
    Debug.Log("pinch in");
}
else if(ratio < previousRatio)
{
    Debug.Log("pinch out");
}

previousRatio = ratio;

or again could directly use the distance and do

if(distance > previousDistance)
{
    Debug.Log("pinch in");
}
else if(distance < previousDistance)
{
    Debug.Log("pinch out");
}

previousDistance = distance;
  • Related