Unity在移动端iphone/ipad上的触屏手势

这几天做ipad的项目时,遇到触屏手势识别操作问题,这里介绍双指控制的缩放和左右移动3D物体,C#代码如下所示:

using UnityEngine;
using System.Collections;

public class MoveAndPinch : MonoBehaviour {
    
    public Transform target;//目标
    float scale;
    private float moveSpeed = 10f;//鼠标移动摄像机速度

    void Start () {
        distance = (transform.position - target.position).magnitude;
   
    }

    Vector3 s1;
    Vector3 s2;

    void Update () {
   
        if (Input.touchCount == 2) 
        {
            if (Input.GetTouch (0).phase == TouchPhase.Moved && Input.GetTouch (1).phase == TouchPhase.Moved) {
                if (s1 != Vector3.zero && s2 != Vector3.zero) {//触摸第一帧s1、s2都为Vector3.zero不执行
                    Vector3 v = Input.GetTouch (0).position;
                    float f = Vector3.Angle (v - s1, Vector3.right);

                    if (f > 45 && f < 135) {//缩放
                        
                        if (distance != 0) {
                            scale = Vector3.Distance (Input.GetTouch (0).position, Input.GetTouch (1).position) / distance;
                            if (scale > 1) {//放大
                                scale = scale * 1.2f;
                            }
                            if (scale < 1) {//缩小
                                scale = scale / 1.2f;       
                            }
                            
target.localScale = new Vector3 (target.localScale.x * scale, target.localScale.y * scale, target.localScale.z * scale);

                        }
                        distance = Vector3.Distance (Input.GetTouch (0).position, Input.GetTouch (1).position);

                    } else {//移动

                        if (f < 45) { 
                            target.position = target.position + Vector3.right * Time.deltaTime * moveSpeed;

                        } else {
                            target.position = target.position + Vector3.left * Time.deltaTime * moveSpeed;
                        }

                    }
                }
            }

                    s1 = Input.GetTouch (0).position;//记录本帧触摸点位置在下一帧使用
                    s2 = Input.GetTouch (1).position;

                    if (Input.GetTouch (0).phase == TouchPhase.Ended || Input.GetTouch (1).phase == TouchPhase.Ended) {//触摸最后一帧s1、s2设为Vector3.zero
                        s1 = new Vector3 (0, 0, 0);
                        s2 = new Vector3 (0, 0, 0);
                    }              
        }
    }

}


猜你喜欢

转载自blog.csdn.net/elegentbeauty/article/details/59566423
今日推荐