NLDClient-yudde/ProjectNLD/Assets/Code/Scripts/Framework/UI/ButtonUpDrag.cs

183 lines
4.3 KiB
C#

using System;
using Framework;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ButtonUpDrag: MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
private bool _isPressed;
private bool _isLastFramePressed;
private float _pressedTime;
private const float MinDelta = 0.01f;
private const float MinLongPressTime = 0.35f;
public static float MinUpDelta = 10f * (Screen.height / 1080f);
private float _maxHorDelta = 0f;
private bool _bUpDrag;
private bool _bLongPress;
private bool _bOnClick;
public delegate void OnUpDrag();
public delegate void OnLongPress();
public delegate void OnClick();
public delegate void OnPointUp();
public delegate void OnPointDown();
public OnPointUp onPointUp;
public OnPointDown onPointDown;
public OnUpDrag onUpDrag;
public OnLongPress onLongPress;
public OnClick onClick;
private Vector2 _startPos;
private Vector2 _curPos;
public void AddPointerUp(Action action)
{
onPointUp += () =>
{
action?.Invoke();
};
}
public void AddPointerDown(Action action)
{
onPointDown += () =>
{
action?.Invoke();
};
}
public void AddLongPress(Action action)
{
onLongPress += () =>
{
action?.Invoke();
};
}
public void AddUpDrag(Action action)
{
onUpDrag += () =>
{
action?.Invoke();
};
}
public void AddUpDrag<T>(Action<T> action, T param)
{
onUpDrag += () =>
{
action?.Invoke(param);
};
}
public void OnPointerDown(PointerEventData eventData)
{
_isPressed = true;
_bLongPress = true;
_bUpDrag = true;
_startPos = eventData.pressPosition;
}
public void OnPointerUp(PointerEventData eventData)
{
// _isPressed = false;
// _bLongPress = true;
// _bUpDrag = true;
}
private void Awake()
{
InputManager.Instance.OnFingerUpUI += _OnPutUp;
InputManager.Instance.OnFingerUp += _OnPutUp;
}
private void OnDestroy()
{
if (InputManager.Instance)
{
InputManager.Instance.OnFingerUpUI -= _OnPutUp;
InputManager.Instance.OnFingerUp -= _OnPutUp;
}
}
private void Update()
{
if (!_isPressed)
{
_bOnClick = false;
_isLastFramePressed = false;
_pressedTime = 0f;
_maxHorDelta = 0f;
return;
}
if (_isPressed)
{
_curPos = InputManager.Instance.GetTouchPosition();
//长按
if (_bLongPress)
{
var disSqr = (_curPos - _startPos).sqrMagnitude;
if (disSqr > MinDelta)
{
_bLongPress = false;
_bOnClick = false;
}
else
{
if (_pressedTime > MinLongPressTime)
{
onLongPress?.Invoke();
_bLongPress = false;
}
}
}
//上滑
if (_bUpDrag)
{
var disSqrY = Mathf.Sqrt(_curPos.y - _startPos.y);
var disSqrX = Mathf.Sqrt(_curPos.x - _startPos.x);
if (_maxHorDelta < disSqrX)
{
_maxHorDelta = disSqrX;
}
if (_maxHorDelta < MinUpDelta)
{
if (disSqrY > MinUpDelta && _maxHorDelta < MinUpDelta)
{
onUpDrag?.Invoke();
_bUpDrag = false;
}
}
}
_pressedTime += Time.deltaTime;
if (!_isLastFramePressed)
{
_isLastFramePressed = true;
}
}
}
private void _OnPutUp(Vector2 pos)
{
if (_isPressed)
{
_isPressed = false;
_bLongPress = true;
_bUpDrag = true;
}
}
public void RemoveAll()
{
}
}