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;
    }
}
相关推荐
_Cherry|3 小时前
Unity中使用AVPRO播放视频
unity·c#·音视频
落羽的落羽4 小时前
【Linux系统】进程终止、进程等待与进程替换的概念与实现
linux·服务器·c++·人工智能·深度学习·机器学习·游戏引擎
世洋Blog16 小时前
Unity中图片的内存中占用大小、AB占用大小、内存形式
unity·游戏引擎
熬夜敲代码的小N16 小时前
Unity热更新技术详解
unity·游戏引擎
地狱为王1 天前
Cesium for Unity 去除Cesium Logo
unity·游戏引擎·cesium
BuHuaX1 天前
Lua入门
开发语言·unity·junit·c#·游戏引擎·lua
wonder135791 天前
RectTransform位置计算方法和UI自适应
ui·unity·ugui
世洋Blog1 天前
Unity发布自己的插件包
unity·游戏引擎
ytttr8732 天前
基于C#的CAN总线数据解析BMS上位机
android·unity·c#