Unity 拖动UI到指定位置与别UI匹配

2023-05-20  本文已影响0人  玄策丶

1、拖动UI脚本(挂载在每个需要拖动的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;  //临时记录点击点与UI的相对位置

    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");
        }

        //检测所有名字位置是否正确
        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;    //工具名字对应的位置按钮
    void Awake()
    {
        Ins = this;
    }

    /// <summary>
    /// 检查名字是否都对应上
    /// </summary>
    public void CheckAllRightPoint()
    {
        foreach (var item in BtnGJ)
        {
            if (!item.GetComponent<DragUI>().isRightPoint)
            {
                StepManager.Ins.BtnNext.gameObject.SetActive(false);
                return;
            }
        }
        StepManager.Ins.ShowBtnNext();
    }
}
上一篇下一篇

猜你喜欢

热点阅读