U3D手指拖动指南

使用UGUI+Event.current

using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections;
using System.Collections.Generic;

public class DragAround : MonoBehaviour
{
    private Vector2 touchFirst = Vector2.zero; //手指开始按下的位置

    private Vector2 touchSecond = Vector2.zero; //手指拖动的位置

    private float timer = 0;//时间计数器  

    public float offsetTime = 0.02f;//判断的时间间隔 

    public float slidingDistance = 5f;//最小偏移量

    //继承于支撑更新的更新事件
    public class MouseEvent : EventsNotify
    {
        public static  string Name => "MouseUp";
        public MouseEvent()
        {
        }
    }

    void Start()
    {
        Input.multiTouchEnabled = false;
    }

    void OnGUI()   // 滑动方法
    {
        //判断当前手指是按下事件 
        if (Event.current.type == EventType.MouseDown)
        {
            touchFirst = Event.current.mousePosition;//记录开始按下的位置
            touchSecond = touchFirst;
            //MainGameProp.Inst.touchMoveDistance = Vector2.zero;
            //Debug.Log("滑动开始");
            MainGameProp.Inst.slide = slideVector.nullVector;
        }

        //判断当前手指是拖动事件
        if (Event.current.type == EventType.MouseDrag)
        {
            timer += Time.deltaTime;  //计时器
            if (timer > offsetTime)
            {
                timer = 0;
                touchFirst = touchSecond;
                touchSecond = Event.current.mousePosition; //记录结束下的位置
                //Debug.Log(touchFirst.x + "            " + touchSecond.x);
                Vector2 _slideDirection = touchSecond - touchFirst;
                MainGameProp.Inst.touchMoveDistance = _slideDirection;
                //if (_slideDirection.x > _slideDirection.y)
                //{
                //    if (_slideDirection.x >= 0) MainGameProp.Inst.slide = slideVector.right;
                //    else MainGameProp.Inst.slide = slideVector.left;
                //}
                //else
                //{
                //    if (_slideDirection.y >= 0) MainGameProp.Inst.slide = slideVector.up;
                //    else MainGameProp.Inst.slide = slideVector.down;
                //}
                //Debug.Log("移动距离:" + slideDirection.x);
            }
        }
        else
        {
            MainGameProp.Inst.touchMoveDistance = Vector2.zero;
            //MainGameProp.Inst.slide = slideVector.nullVector;
        }


        if (Event.current.type == EventType.MouseUp)
        {
            MainGameProp.Inst.touchMoveDistance = Vector2.zero;
            //MainGameProp.Inst.slide = slideVector.nullVector;
            if (MainGameProp.Inst.zombiePool.Count > 0)
            {
                //暂时屏蔽手动跳跃
                //NotifierDispense.Notify(MouseEvent.Name, new MouseEvent());
            }
           
            //Debug.Log("滑动结束");
        }

    }


}

 

你可能感兴趣的:(U3D)