Check if UI elements/RectTransform are overlapping

前端 未结 2 1255
孤城傲影
孤城傲影 2020-12-17 03:21

I\'d like to know how I check whether two UI Panels on my Unity Canvas are overlapping each other.

Currently I am doing this by comparing the canvas elements Rects

相关标签:
2条回答
  • 2020-12-17 03:47

    Convert the RectTransform to Rect then check if it overlaps.

    Here is a simple function that can do that:

    bool rectOverlaps(RectTransform rectTrans1, RectTransform rectTrans2)
    {
        Rect rect1 = new Rect(rectTrans1.localPosition.x, rectTrans1.localPosition.y, rectTrans1.rect.width, rectTrans1.rect.height);
        Rect rect2 = new Rect(rectTrans2.localPosition.x, rectTrans2.localPosition.y, rectTrans2.rect.width, rectTrans2.rect.height);
    
        return rect1.Overlaps(rect2);
    }
    

    Usage:

    public RectTransform uiRect1;
    public RectTransform uiRect2;
    
    void Update()
    {
        if (rectOverlaps(uiRect1, uiRect2))
        {
            Debug.Log("Overlaps");
        }else
        {
            Debug.Log("Does not Overlap");
        }
    }
    

    Even better, make it an extension method:

    public static class ExtensionMethod
    {
        public static bool rectOverlaps(this RectTransform rectTrans1, RectTransform rectTrans2)
        {
            Rect rect1 = new Rect(rectTrans1.localPosition.x, rectTrans1.localPosition.y, rectTrans1.rect.width, rectTrans1.rect.height);
            Rect rect2 = new Rect(rectTrans2.localPosition.x, rectTrans2.localPosition.y, rectTrans2.rect.width, rectTrans2.rect.height);
    
            return rect1.Overlaps(rect2);
        }
    }
    

    Now, you can do

    public RectTransform uiRect1;
    public RectTransform uiRect2;
    
    void Update()
    {
        if (uiRect1.rectOverlaps(uiRect2))
        {
    
        }
    
        //OR
    
        if (uiRect2.rectOverlaps(uiRect1))
        {
    
        }
    }
    
    0 讨论(0)
  • 2020-12-17 03:52

    Updated version considering scale of the rectTransform.

    public static class RectTransformExtensions
    {
    
        public static bool Overlaps(this RectTransform a, RectTransform b) {
            return a.WorldRect().Overlaps(b.WorldRect());
        }
        public static bool Overlaps(this RectTransform a, RectTransform b, bool allowInverse) {
            return a.WorldRect().Overlaps(b.WorldRect(), allowInverse);
        }
    
        public static Rect WorldRect(this RectTransform rectTransform) {
            Vector2 sizeDelta = rectTransform.sizeDelta;
            float rectTransformWidth = sizeDelta.x * rectTransform.lossyScale.x;
            float rectTransformHeight = sizeDelta.y * rectTransform.lossyScale.y;
    
            Vector3 position = rectTransform.position;
            return new Rect(position.x - rectTransformWidth / 2f, position.y - rectTransformHeight / 2f, rectTransformWidth, rectTransformHeight);
        }
    }
    
    0 讨论(0)
提交回复
热议问题