直接上代碼吧,不想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));
}
/// <summary>
/// 相機傳入主要取決于rt都畫布,如果畫布使用camera模式员萍,則傳入對應(yīng)的相機,反之為null,注意:wordspace模式我沒有測試拣度,不在此次記錄范圍
/// </summary>
/// <param name="rt"></param>
/// <param name="cam"></param>
/// <returns></returns>
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;
}
}
下面為測試結(jié)果:
測試結(jié)果1:
測試結(jié)果2:
注意:上圖的畫布使用Overlay模式碎绎,所以Camera參數(shù)直接傳入null!?构筋帖!