Unity判断两个ui是否相交(矩形相交)

直接上代码吧,不想bb了

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour
{
    public RectTransform rt1;
    public RectTransform rt2;

    // Start is called before the first frame update
    void Start()
    {
        Rect rect1 = RectTransToScreenPos(rt1, null);
        Rect rect2 = RectTransToScreenPos(rt2, null);

        Debug.Log(rect1.Overlaps(rect2));
    }


    /// 
    /// 相机传入主要取决于rt都画布,如果画布使用camera模式,则传入对应的相机,反之为null,注意:wordspace模式我没有测试,不在此次记录范围
    /// 
    /// 
    /// 
    /// 
    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;
    }
}

下面为测试结果:

测试结果1:

image.png

测试结果2:

image.png

注意:上图的画布使用Overlay模式,所以Camera参数直接传入null!!!

最后,附上unity判断相交方法的源码供大家参考:

image.png

你可能感兴趣的:(Unity判断两个ui是否相交(矩形相交))