Unity中实现UGUI中的UI托拽功能

有些时候我们需要将打开的窗口进行托拽,一下脚本就可以实现


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
/// <summary>
/// 主要用于窗口的拖动、、应用鼠标按下还有拖动接口
/// </summary>
public class DraggableWindow : MonoBehaviour, IDragHandler,IPointerDownHandler
{
    public RectTransform canvas;
    private RectTransform imgRect;
    Vector2 offset = new Vector2();
    private void Start()
    {
        imgRect = GetComponent<RectTransform>();
    }
    public void OnPointerDown(PointerEventData eventData)
    {
        Vector2 mouseDown = eventData.position;
        Vector2 mouseGuiPos = new Vector2();
        bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, mouseDown, eventData.enterEventCamera, out mouseGuiPos);
        if (isRect)   //如果在
        {
            //计算图片中心和鼠标点的差值
            offset = imgRect.anchoredPosition - mouseGuiPos;
        }
    }
    public void OnDrag(PointerEventData eventData)
    {
        Vector2 mouseDrag = eventData.position;
        Vector2 UguiPos = new Vector2();
        bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, mouseDrag, eventData.pressEventCamera, out UguiPos);
        if (isRect)
        {
            imgRect.anchoredPosition = offset + UguiPos;
        }
    }
   
}

猜你喜欢

转载自blog.csdn.net/qq_38112703/article/details/79880574