Unity在屏幕上滑动

使用ui的Image,放在最上层,进行检测是否在ui上滑动

创建一个Image,设置为全屏,挂在下方脚本即可。

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class SwipeDetector03 : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    [Header("滑动设置")]
    [SerializeField] private float swipeThreshold = 50f; // 滑动阈值(像素)

    private Vector2 startPosition;
    private bool isDragging = false;

    // 开始拖拽
    public void OnBeginDrag(PointerEventData eventData)
    {
        startPosition = eventData.position;
        isDragging = true;
        //Debug.Log("开始滑动");
    }

    // 拖拽中
    public void OnDrag(PointerEventData eventData)
    {
        // 可以在这里添加实时拖拽效果
    }

    // 结束拖拽
    public void OnEndDrag(PointerEventData eventData)
    {
        if (!isDragging) return;

        Vector2 endPosition = eventData.position;
        float swipeDistance = endPosition.x - startPosition.x;

        //Debug.Log("滑动距离: " + swipeDistance);

        // 判断滑动距离是否超过阈值
        if (Mathf.Abs(swipeDistance) > swipeThreshold)
        {
            if (swipeDistance > 0)
            {
                // 向右滑动
                //Debug.Log("下一页");
                // 在这里调用你的下一页逻辑

                (UiPanel.Instance.GetUiPanelForType(UiPanelType.TwoLevelPanel03) as TwoLevelPanel03).
                    NextPanel();

            }
            else
            {
                // 向左滑动
                //Debug.Log("上一页");
                // 在这里调用你的上一页逻辑

                (UiPanel.Instance.GetUiPanelForType(UiPanelType.TwoLevelPanel03) as TwoLevelPanel03).
                    PreviousPanel();
            }
        }

        isDragging = false;
    }
}
相关推荐
我的offer在哪里14 小时前
示例 Unity 项目结构(Playable Game Template)
unity·游戏引擎
淡海水17 小时前
【节点】[Branch节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·branch
在路上看风景17 小时前
4.6 显存和缓存
unity
Zik----20 小时前
简单的Unity漫游场景搭建
unity·游戏引擎
在路上看风景1 天前
4.5 顶点和片元
unity
在路上看风景2 天前
31. Unity 异步加载的底层细节
unity
天人合一peng2 天前
Unity中做表头时像work中整个调整宽窄
unity
小李也疯狂2 天前
Unity 中的立方体贴图(Cubemaps)
unity·游戏引擎·贴图·cubemap
牛掰是怎么形成的2 天前
Unity材质贴图引用陷阱:包体暴涨真相
unity·材质·贴图
呆呆敲代码的小Y2 天前
【Unity工具篇】| 超实用工具LuBan,快速上手使用
游戏·unity·游戏引擎·unity插件·luban·免费游戏·游戏配置表