天天看点

Unity移动端手势操作——缩放3D物体

自己写的一套用于Unity移动端手势操作的判断,主要有单指移动3D物体、单指旋转3D物体、双指缩放3D物体,这里首先分开介绍双指缩放3D物体,如下所示:

using UnityEngine;
using System.Collections;

public class ZoomControl : GestureControl
{
    //记录上一次手机触摸位置判断用户是在左放大还是缩小手势  
    private Vector2 oldPosition1;
    private Vector2 oldPosition2;
    //实时大小
    Vector3 RealScale = new Vector3(1f, 1f, 1f);
    //原始大小
    float InitialScale = 0;
    //缩放速度
    public float ScaleSpeed = 0.1f;
    //缩放比例
    public float MaxScale = 2.5f;
    public float MinScale = 0.5f;

    void Start()
    {
        //获取物体最原始大小
        InitialScale = this.transform.localScale.x;
    }

    protected override void InputCheck()
    {
        #region 多点触摸缩放(真实模型缩放)
        
        if (Input.touchCount > 1)
        {
            status = 2;
            StartCoroutine(CustomOnMouseDown());
        }
        #endregion
    }

    IEnumerator CustomOnMouseDown()
    {
        //当检测到一直触碰时,会不断循环运行
        while (Input.GetMouseButton(0))
        {
            //实时记录模型大小
            RealScale = this.transform.localScale;
            if (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved)
            {
                //触摸位置
                Vector3 tempPosition1 = Input.GetTouch(0).position;
                Vector3 tempPosition2 = Input.GetTouch(1).position;

                //函数返回真为放大,返回假为缩小 
                if (isEnlarge(oldPosition1, oldPosition2, tempPosition1, tempPosition2))
                {
                    //判断是否超过边界
                    if (RealScale.x < InitialScale * MaxScale)
                    {
                        this.transform.localScale += this.transform.localScale * ScaleSpeed;
                    }
                }
                else
                {
                    //判断是否超过边界
                    if (RealScale.x > InitialScale * MinScale)
                    {
                        this.transform.localScale -= this.transform.localScale * ScaleSpeed;
                    }
                }
                //备份上一次的触摸位置
                oldPosition1 = tempPosition1;
                oldPosition2 = tempPosition2;
            }

            yield return new WaitForFixedUpdate();
        }
    }

    //记录手指位置与初始位置是缩小或放大
    bool isEnlarge(Vector2 oP1, Vector2 oP2, Vector2 nP1, Vector2 nP2)
    {
        float leng1 = Mathf.Sqrt((oP1.x - oP2.x) * (oP1.x - oP2.x) + (oP1.y - oP2.y) * (oP1.y - oP2.y));
        float leng2 = Mathf.Sqrt((nP1.x - nP2.x) * (nP1.x - nP2.x) + (nP1.y - nP2.y) * (nP1.y - nP2.y));
        if (leng1 < leng2)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}