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

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

public class MoveControl : GestureControl
{  
    protected override void InputCheck()
    {
        //单指移动
        if (Input.touchCount == 1)
        {
            //触碰按住3D物体不动1秒后物体随手指一起移动
            if (Input.GetTouch(0).phase == TouchPhase.Stationary)
            {
                TouchTime += Time.deltaTime;
                if (TouchTime > 1)
                {
                    status = 0;
                }
            }
            if (status == 0)
            {
                StartCoroutine(CustomOnMouseDown());
            }
        }
    }
    IEnumerator CustomOnMouseDown()
    {
        //将物体由世界坐标系转化为屏幕坐标系,由vector3 结构体变量ScreenSpace存储,以用来明确屏幕坐标系Z轴的位置
        Vector3 ScreenPoint = Camera.main.WorldToScreenPoint(transform.position);

        //由于鼠标的坐标系是二维的,需要转化成三维的世界坐标系;
        Vector3 WorldPostion = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, ScreenPoint.z));

        //三维的情况下才能来计算鼠标位置与物体的距离
        Vector3 distance = transform.position - WorldPostion;

        //当鼠标左键按下时
        while (Input.GetMouseButton(0))
        {
            //得到现在鼠标的二维坐标系位置
            Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, ScreenPoint.z);
            //将当前鼠标的2维位置转化成三维的位置,再加上鼠标的移动距离
            Vector3 CurPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + distance;
            //CurPosition就是物体应该的移动向量赋给transform的position属性		
            transform.position = CurPosition;
            //鼠标释放前都起作用
            yield return new WaitForFixedUpdate();
        }
    }
}

你可能感兴趣的:(Unity手势操作,Unity移动端技术开发)