unity3d 检测手指是否向内或向外收缩

lnxxn5zx  于 2023-01-09  发布在  其他
关注(0)|答案(1)|浏览(130)

我正在使用触摸输入来执行捏夹功能。捏夹功能正常,但我想检测两个手指是捏入(彼此靠近)还是捏出(彼此远离)。如何做到这一点?
我已经尝试过存储当前比率与先前比率以便检查下一次迭代,但由于我在每一帧都存储它,因此它会波动。此外,如果用户从未抬起手指,该如何工作?

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;
               
            }
 
        }
 
    }
}
guykilcj

guykilcj1#

对于总的最终收缩方向,可以简单地表示为

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

或者直接按距离计算

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

如果你宁愿它的框架明智的,不管整体结果,我认为你应该实际上罚款做

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

previousRatio = ratio;

也可以直接用距离来计算

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

previousDistance = distance;

相关问题