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

相关推荐
★YUI★1 小时前
学习游戏制作记录(剑投掷技能)7.26
学习·游戏·unity·c#
小乖兽技术1 小时前
C#与C++交互开发系列(二十四):WinForms 应用中嵌入C++ 原生窗体
c++·c#·交互
I'mSQL3 小时前
C#与WPF使用mvvm简单案例点击按钮触发弹窗
开发语言·c#·wpf
工藤新一OL3 小时前
把xml的格式从utf-8-bom转为utf-8
xml·c#·asp.net·.netcore·visual studio
呉師傅3 小时前
佳能iR-ADV C5560复印机如何扫描文件到电脑
运维·网络·windows·计算机外设·电脑
henreash4 小时前
NLua和C#交互
开发语言·c#·交互
SAJalon7 小时前
C#集合全面解析
c#
SAJalon9 小时前
C#数组全面解析
c#
henreash10 小时前
xLua和C#交互
开发语言·c#·交互
慢慢沉19 小时前
C#(基本语法)
c#