在unity UI开发中滑动是用的比较多的功能了,有时候我们需要监听一些事件,例如左滑右滑,然后来进行我们的逻辑操作,那么就可以用到下面的脚本了,
1、首先我们需要创建一个Image,用来接收UI事件;
2、接着只需要在这个Image上添加上我们的脚本,这时候运行程序测试发现,就可以监听到左滑右滑上滑下滑事件了(支持鼠标滑动和触摸屏滑动)
/***********************************
* Description:描述
* Mountpoint:挂载点 挂载在图片上面
* File Name: HuaDongTool.cs
* Version:版本
* Author:LJF
* E_mail: [email protected]
* CreateTime: 2021/10/12 18:18:35
***********************************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
namespace LJF
{
//规范命名、合理封装、限制访问修饰符
public class HuaDongTool : MonoBehaviour,IBeginDragHandler,IEndDragHandler,IDragHandler
{
public float dis = 150;//滑动像素限制范围
private Vector3 beginPos;
private Vector3 endPos;
[Header("左滑事件")]
public UnityEvent left_Evt;
[Header("右滑事件")]
public UnityEvent right_Evt;
[Header("上滑事件")]
public UnityEvent up_Evt;
[Header("下滑事件")]
public UnityEvent down_Evt;
private void Start()
{
}
private void OnDragStart()//开始拖拽
{
//Debug.Log(1);
beginPos = Input.mousePosition;
}
private void OnDragEnd()//结束脱宅
{
//Debug.Log(1);
endPos = Input.mousePosition;
float hor = endPos.x - beginPos.x;
float vor = endPos.y - beginPos.y;
//左右判断
if (Mathf.Abs(hor)>=dis)
{
if (hor>0)//右滑
{
Debug.Log("右");
right_Evt?.Invoke();
}
else//左滑
{
Debug.Log("左");
left_Evt?.Invoke();
}
}
//上下判断
if (Mathf.Abs(vor) >= dis)
{
if (vor > 0)//上滑
{
Debug.Log("上");
up_Evt?.Invoke();
}
else//下滑
{
Debug.Log("下");
down_Evt?.Invoke();
}
}
}
public void OnBeginDrag(PointerEventData eventData)
{
OnDragStart();
}
public void OnEndDrag(PointerEventData eventData)
{
OnDragEnd();
}
public void OnDrag(PointerEventData eventData)
{
}
}
}