Unity中,在按下、滑动、抬起时发出相应事件,用于输入控制
2023-07-26 本文已影响0人
全新的饭
说明:MyInput需挂在一个全屏Img(设置为透明)上。
![](https://img.haomeiwen.com/i10492731/d02909a59513cf7c.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;
}
}