Unity 鼠标点击或触摸任意拖动UGUI的方法

在Unity中,如果要通过鼠标拖到UI组件或者触摸移动UI组件,可以使用EventSystems下的方法。

具体实现如下:

新建一个脚本,DragController.cs:

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

public class DragController : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
{
    private RectTransform tran;
    private Vector2 pointerOffset;

    private void Awake()
    {
        tran = GetComponent<RectTransform>();
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        // 计算触摸点与拖动对象的偏移量
        pointerOffset = eventData.position - (Vector2)tran.position;
    }

    public void OnDrag(PointerEventData eventData)
    {
        // 更新拖动对象的位置
        tran.position = eventData.position - pointerOffset;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        // 重置偏移量
        pointerOffset = Vector2.zero;
    }
}

然后把该脚本拉到UI组件中,运行后我们可以通过鼠标拖到UI组件,在触摸屏上,我们也可以通过触摸UI组件拖动。

效果如:

Unity 鼠标点击或触摸任意拖动UGUI的方法

相关推荐
在路上看风景1 小时前
1.12 Memory Profiler Package - Summary
unity
xiaowu0802 小时前
策略模式-不同的鸭子的案例
开发语言·c#·策略模式
VisionPowerful5 小时前
九.弗洛伊德(Floyd)算法
算法·c#
ArabySide5 小时前
【C#】 资源共享和实例管理:静态类,Lazy<T>单例模式,IOC容器Singleton我们该如何选
单例模式·c#·.net core
SmalBox6 小时前
【URP】Unity Shader Tags
unity·渲染
gc_22997 小时前
C#测试调用OpenXml操作word文档的基本用法
c#·word·openxml
almighty2710 小时前
C#海康车牌识别实战指南带源码
c#·海康车牌识别·c#实现车牌识别·车牌识别源码·c#车牌识别
极客柒13 小时前
Unity 塔防自用可视化路点寻路编辑器
unity·编辑器·游戏引擎
c#上位机14 小时前
wpf之TextBlock
c#·wpf
程序猿多布14 小时前
Unity AssetBundle详解
unity·assetbundle