说明:MyInput需挂在一个全屏Img(设置为透明)上。
image.png
MyInput.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class MyInput : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
{
private const int DefaultId = -100;
private int _curId;
private Vector2 _centerPos;
// 位置
public event Action<Vector2> PointerDownEvent;
// 朝向
public event Action<Vector2> PointerDragEvent;
// 位置
public event Action<Vector2> PointerUpEvent;
public void Init()
{
ResetId();
}
public void MyDestroy()
{
}
public void OnPointerDown(PointerEventData eventData)
{
if (_curId == DefaultId)
{
_curId = eventData.pointerId;
_centerPos = eventData.position;
PointerDownEvent?.Invoke(_centerPos);
}
}
public void OnDrag(PointerEventData eventData)
{
if (_curId == eventData.pointerId)
{
var curDir = (eventData.position - _centerPos).normalized;
PointerDragEvent?.Invoke(curDir);
}
}
public void OnPointerUp(PointerEventData eventData)
{
if (_curId == eventData.pointerId)
{
ResetId();
PointerUpEvent?.Invoke(eventData.position);
}
}
private void ResetId()
{
_curId = DefaultId;
}
}
网友评论