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;
    }
}
相关推荐
Aman19841 小时前
Claude Code做Unity项目移植(一):从零散工具到团队式
unity·游戏开发·vibe coding·claude code·项目迁移
地狱为王3 小时前
Unity使用VoxLock实现语音隔离
unity·游戏引擎·音频处理·voxlock
Jmyd01236 小时前
博物馆数字展厅系统架构设计:实景采集到云渲染全链路
unity·系统架构·博物馆·数字展厅·博物馆数字化
解决小子7 小时前
【虚幻引擎】【GAS】模块详解
游戏引擎·虚幻·gas
一只大鸽子8 小时前
游戏开发笔记0-Godot启动
笔记·游戏引擎·godot
weixin_4242946710 小时前
对于未加入 Script Execution Order 的脚本
unity
暴走约伯10 小时前
【VFX工具链源码拆解 03】告别机械劳动(下):材质字典映射批处理与智能纹理槽识别
unity·游戏引擎·材质
Wanda121410 小时前
机器人与机电一体化3D数字孪生机器-Day9
人工智能·3d·unity·机器人·数字孪生
暴走约伯11 小时前
【VFX工具链源码拆解 01】总体架构:大型项目特效流程的程序化落地
开发语言·经验分享·3d·unity·架构·游戏引擎
Oiiouui1 天前
Godot-GridGame架构DI容器全局联动设计
架构·游戏引擎·godot