C#滑动事件脚本工具

2022-03-21 09:13:01

在unity UI开发中滑动是用的比较多的功能了,有时候我们需要监听一些事件,例如左滑右滑,然后来进行我们的逻辑操作,那么就可以用到下面的脚本了,
1、首先我们需要创建一个Image,用来接收UI事件;
2、接着只需要在这个Image上添加上我们的脚本,这时候运行程序测试发现,就可以监听到左滑右滑上滑下滑事件了(支持鼠标滑动和触摸屏滑动)

/***********************************
*	Description:描述
*	Mountpoint:挂载点 挂载在图片上面
*	File Name:  HuaDongTool.cs
*	Version:版本
*	Author:LJF
*	E_mail: 1061986324@qq.com
*	CreateTime: 2021/10/12 18:18:35
***********************************/usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;usingUnityEngine.Events;usingUnityEngine.EventSystems;namespaceLJF{//规范命名、合理封装、限制访问修饰符publicclassHuaDongTool:MonoBehaviour,IBeginDragHandler,IEndDragHandler,IDragHandler{publicfloat dis=150;//滑动像素限制范围privateVector3 beginPos;privateVector3 endPos;[Header("左滑事件")]publicUnityEvent left_Evt;[Header("右滑事件")]publicUnityEvent right_Evt;[Header("上滑事件")]publicUnityEvent up_Evt;[Header("下滑事件")]publicUnityEvent down_Evt;privatevoidStart(){}privatevoidOnDragStart()//开始拖拽{//Debug.Log(1);
            beginPos= Input.mousePosition;}privatevoidOnDragEnd()//结束脱宅{//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();}}}publicvoidOnBeginDrag(PointerEventData eventData){OnDragStart();}publicvoidOnEndDrag(PointerEventData eventData){OnDragEnd();}publicvoidOnDrag(PointerEventData eventData){}}}

在这里插入图片描述

  • 作者:码农李瓜皮
  • 原文链接:https://blog.csdn.net/weixin_43956644/article/details/124822981
    更新时间:2022-03-21 09:13:01