Unity 拖動(dòng)UI到指定位置與別UI匹配

1、拖動(dòng)UI腳本(掛載在每個(gè)需要拖動(dòng)的UI上)

using UnityEngine;
using UnityEngine.EventSystems;

public class DragUI : MonoBehaviour, IDragHandler, IPointerDownHandler,IPointerUpHandler
{
    Vector3 startPoint;

    public int BtnIndex;

    public bool isRightPoint;

    private void Start()
    {
        startPoint = transform.position;
    }
    private Vector2 offsetPos;  //臨時(shí)記錄點(diǎn)擊點(diǎn)與UI的相對(duì)位置

    public void OnDrag(PointerEventData eventData)
    {
        transform.position = eventData.position - offsetPos;
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        offsetPos = eventData.position - (Vector2)transform.position;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        if (RectTransToScreenPos(transform.GetComponent<RectTransform>(), null)
            .Overlaps(RectTransToScreenPos(Step2.Ins.Point[BtnIndex].GetComponent<RectTransform>(), null)))
        {
            isRightPoint = true;
            transform.position = Step2.Ins.GJ_Point[BtnIndex].transform.position;
        }
        else
        {
            isRightPoint = false;
            transform.position = startPoint;
            AudioManager.Ins.PlayAudio("cuowuSound");
        }

        //檢測(cè)所有名字位置是否正確
        Step2.Ins.CheckAllRightPoint();

    }

    public static Rect RectTransToScreenPos(RectTransform rt, Camera cam)
    {
        Vector3[] corners = new Vector3[4];
        rt.GetWorldCorners(corners);
        Vector2 v0 = RectTransformUtility.WorldToScreenPoint(cam, corners[0]);
        Vector2 v1 = RectTransformUtility.WorldToScreenPoint(cam, corners[2]);
        Rect rect = new Rect(v0, v1 - v0);
        return rect;
    }
}

2、UI控制腳本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Step2 : MonoBehaviour
{
    public static Step2 Ins;

    public Button[] BtnGJ;          //工具名字按鈕
    public Image[] GJ_Point;    //工具名字對(duì)應(yīng)的位置按鈕
    void Awake()
    {
        Ins = this;
    }

    /// <summary>
    /// 檢查名字是否都對(duì)應(yīng)上
    /// </summary>
    public void CheckAllRightPoint()
    {
        foreach (var item in BtnGJ)
        {
            if (!item.GetComponent<DragUI>().isRightPoint)
            {
                StepManager.Ins.BtnNext.gameObject.SetActive(false);
                return;
            }
        }
        StepManager.Ins.ShowBtnNext();
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容