首页 > 解决方案 > Unity 多点触控(捏合)缩放对象

问题描述

我正在尝试使用多点触控(捏)来缩放对象。
它工作正常,但是当我放开 2 次触摸并尝试再次放大和缩小时,
对象一直试图回到其原始比例。

我使用了下面的代码。

if (Input.touchCount == 2 && Input.GetTouch(0).phase == TouchPhase.Moved && Input.GetTouch(1).phase == TouchPhase.Moved)
{
    Touch touchZero = Input.GetTouch(0); 
    Touch touchOne = Input.GetTouch(1);

    Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
    Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;

    float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
    float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;

    float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;
    float pinchAmount = deltaMagnitudeDiff * 0.02f * Time.deltaTime;
    objectImRotating.transform.localScale += new Vector3(pinchAmount, pinchAmount, pinchAmount);
}

标签: c#unity3d

解决方案


我不知道问题的原因,但我会这样做:而不是使用逐帧添加进行缩放,而是执行类似的操作

private Vector2 initialDistance;
private Vector3 initialScale;

private void Update()
{
    if (Input.touchCount == 2)
    {
        var touchZero = Input.GetTouch(0); 
        var touchOne = Input.GetTouch(1);

        // if one of the touches Ended or Canceled do nothing
        if(touchZero.phase == TouchPhase.Ended || touchZero.phase == TouchPhase.Canceled  
           || touchOne.phase == TouchPhase.Ended || touchOne.phase == TouchPhase.Canceled) 
        {
            return;
        }

        // It is enough to check whether one of them began since we
        // already excluded the Ended and Canceled phase in the line before
        if(touchZero.phase == TouchPhase.Began || touchOne.phase == TouchPhase.Began)
        {
            // track the initial values
            initialDistance = Vector2.Distance(touchZero.position, touchOne.position);
            initialScale = objectImRotating.transform.localScale;
        }
        // else now is any other case where touchZero and/or touchOne are in one of the states
        // of Stationary or Moved
        else
        {
            // otherwise get the current distance
            var currentDistance = Vector2.Distance(touchZero.position, touchOne.position);

            // A little emergency brake ;)
            if(Mathf.Approximately(initialDistance, 0)) return;

            // get the scale factor of the current distance relative to the inital one
            var factor = currentDistance / initialDistance;

            // apply the scale
            // instead of a continuous addition rather always base the 
            // calculation on the initial and current value only
            objectImRotating.transform.localScale = initialScale * factor;
        }
    }
}

在智能手机上打字,但我希望这个想法很清楚


推荐阅读