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("滑動結束");
        }

    }


}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章