欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

图片拖拽和交换位置

程序员文章站 2022-07-14 16:31:04
...

    public void OnBeginDrag(PointerEventData eventData)
    {
        m_OriginSlotTrasnform = transform.parent;  //记录当前Item的父对象位置
        transform.SetParent(m_UICanvasTransform); //防止其它物体阻挡Item的渲染
        m_InventoryGrid.ClearInfo();
    }

    public void OnDrag(PointerEventData eventData)
    {
        DragPos(eventData);
        this.gameObject.GetComponent<Image>().raycastTarget = false; //关闭Item的射线检测


    }

    public void OnEndDrag(PointerEventData eventData)
    {
        SetTargetPosition(eventData);
    }

    private void SetOriginPosition(GameObject item)  //回原位置
    {
        item.transform.SetParent(m_OriginSlotTrasnform);
        item.GetComponent<RectTransform>().anchoredPosition = m_OriginSlotTrasnform.GetComponent<RectTransform>().anchoredPosition;
        item.GetComponent<Image>().raycastTarget = true;
    }
    private void SetTargetPosition(PointerEventData eventData)
    {
        GameObject m_Hit = eventData.pointerCurrentRaycast.gameObject;
        if (eventData.pointerCurrentRaycast.depth == 0)
        {
            SetOriginPosition(gameObject);
            return;
        }
        if (m_Hit.CompareTag(TagsManager.m_InventoryGrid))  //空格子的时候
        {
            gameObject.transform.SetParent(m_Hit.transform);
            gameObject.GetComponent<RectTransform>().anchoredPosition = m_Hit.transform.GetComponent<RectTransform>().anchoredPosition;
            gameObject.GetComponent<Image>().raycastTarget = true;
        }
        else if (m_Hit.CompareTag(TagsManager.m_InventoryItem))
        {
           
            gameObject.transform.SetParent(m_Hit.transform.parent);
            gameObject.GetComponent<RectTransform>().anchoredPosition = m_Hit.transform.parent.GetComponent<RectTransform>().anchoredPosition;
            gameObject.GetComponent<Image>().raycastTarget = true;
            SetOriginPosition(m_Hit);

        }
        else
        {
            SetOriginPosition(gameObject);
        }
    }
    private void DragPos(PointerEventData eventData)
    {
        RectTransform RectItem = gameObject.GetComponent<RectTransform>();
        Vector3 globalMousePos;
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(gameObject.transform as RectTransform, eventData.position, eventData.pressEventCamera, out globalMousePos))
        {
            RectItem.position = globalMousePos;
        }
    }
相关标签: Unity