2017-02-04 174 views
1

我想知道如何檢查我的Unity Canvas上的兩個UI面板是否互相重疊。檢查UI元素/ RectTransform是否重疊

目前我比較畫布元素做這個Rects

畫布設置

  • 渲染模式:屏幕空間 - 相機
  • 像素完美:[是]
  • 渲染相機:主攝像頭
  • 平面距離:100
  • 排序層:默認
  • 順序在層:0

畫布縮放器設置

  • UI縮放模式:定像素尺寸
  • 比例因子:1
  • 參考像素每單位:100

代碼我使用的檢查情況

[Header("Check For Overlap")] 
public RectTransform PlayerBar; 
public RectTransform LeftBar; 
public Rect RectOne; 
public Rect RectTwo; 
public bool overlapping; 

//Check if the two canvas element Rects overlap each other 

public void CheckForOverlap() 
{ 
    overlapping = false; 
    // Convert Canvas RectTransforms to World Rects 
    RectOne = GetWorldRect(LeftBar); 
    RectTwo = GetWorldRect(PlayerBar); 

    if (RectOne.Overlaps(RectTwo)) 
    { 
     overlapping = true; 
    } 
} 


public Rect GetWorldRect(RectTransform rt) 
{ 
    // Get World corners, take top left 
    Vector3[] corners = new Vector3[4]; 
    rt.GetWorldCorners(corners); 
    Vector3 topLeft = corners[0]; 

    // Rect Size ... I'm not sure if this is working correctly? 
    Vector2 size = new Vector2(rt.rect.size.x, rt.rect.size.y); 
    return new Rect(topLeft, size); 
} 

什麼

'重疊' BOOL立即更改爲true。

該矩形的一個返回如(例如)

X -7.5,Y 2.5 W¯¯98.5,H 164.1667

回答

2

轉換的RectTransformRect然後檢查它是否重疊。

下面是一個簡單的函數,可以這樣做:

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

使用

public RectTransform uiRect1; 
public RectTransform uiRect2; 

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

更妙的是,使它的擴展方法:

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

現在,你可以做

public RectTransform uiRect1; 
public RectTransform uiRect2; 

void Update() 
{ 
    if (uiRect1.rectOverlaps(uiRect2)) 
    { 

    } 

    //OR 

    if (uiRect2.rectOverlaps(uiRect1)) 
    { 

    } 
} 
+1

非常感謝,這真的很有用。尤其是擴展方法的附加提示 – Jim