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的方法

相关推荐
从孑开始8 小时前
ManySpeech.MoonshineAsr 使用指南
人工智能·ai·c#·.net·私有化部署·语音识别·onnx·asr·moonshine
YuanlongWang8 小时前
C# 中,依赖注入(DI)的实现方式
c#
SmartSoftHelp开发辅助优化9 小时前
C# WinForm 编程高手:程序,进程,线程。程序,窗体,UI,后台。是如何协调工作的?深度解析>SmartSoftHelp魔法精灵工作室
microsoft·ui·c#
future_studio12 小时前
聊聊 Unity(小白专享、C# 小程序 之 加密存储)
开发语言·小程序·c#
c#上位机12 小时前
MefBootstrapper在Prism引导程序中的使用
c#·wpf·prism
玩泥巴的15 小时前
.NET驾驭Word之力:基于规则自动生成及排版Word文档
c#·word·.net·com互操作
SunnyDays101115 小时前
C# 实现高保真 Excel 转 PDF(无需 Office 环境)
经验分享·c#·excel转pdf
攻城狮CSU16 小时前
C# 数据加载专题 之泛型序列化
java·servlet·c#
爱编程的鱼16 小时前
C# 参数详解:从基础传参到高级应用
开发语言·microsoft·c#
开发游戏的老王17 小时前
虚幻引擎虚拟制片入门教程 之 Sequencer 常用技巧
游戏引擎·虚幻