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

相关推荐
春日见14 分钟前
自动驾驶的四个演进阶段
开发语言·人工智能·驱动开发·matlab·docker·计算机外设
美团骑手阿豪25 分钟前
C#语法:HashSet与List对比,适合场景
unity·c#
wr26 分钟前
Modbus 读写转换
c#
公子小六31 分钟前
基于.NET的Windows窗体编程之WinForms入门简介
windows·microsoft·c#·.net
CSharp精选营32 分钟前
C# 面试高频题:装箱和拆箱是如何影响性能的?
c#·.net·面试题·装箱·拆箱·c#面试题
mzhan0171 小时前
电脑:鼠标
计算机外设·电脑
我是唐青枫1 小时前
C#.NET SpinLock 深入解析:自旋锁原理、使用边界与性能取舍
c#·.net
似水明俊德1 小时前
13-C#.Net-设计模式六大原则-学习笔记
笔记·学习·设计模式·c#·.net
无心水2 小时前
【时间利器】5、多语言时间处理实战:Go/C#/Rust/Ruby统一规范
golang·rust·c#·时间·分布式架构·openclaw·openclaw变现
WHD3062 小时前
苏州服务器维修哪家好/公司推荐
linux·ubuntu·centos·计算机外设·电脑·unix·安全架构