2016-11-12 36 views
0

有沒有辦法檢查Rect變換是否包含點?提前致謝。我試圖Bounds.Contains()和RectTransformUtility.RectangleContainsScreenPoint(),但沒有幫助我Unity Recttransform包含點

private bool AreCoordsWithinUiObject(Vector2 coords, GameObject gameObj) 
{ 
    Bounds bounds = gameObj.GetComponent<Renderer>().bounds; 
    return bounds.Contains(new Vector3(coords.x, coords.y, 0)); 
} 

這樣,我有一個錯誤「沒有附着在物體渲染」,但我已經連接CanvasRenderer到它。

RectTransformUtility.RectangleContainsScreenPoint(gameObj.GetComponent<RectTransform>(), coords); 

此方法總是返回false

if (AreCoordsWithinUiObject(point, lines[i])) 
{ 
    print("contains"); 
} 

線是GameObjects

enter image description here

+0

請包括您嘗試的代碼。你的問題只是一個功能。把代碼不起作用。 「Bounds.Contains」和「RectTransformUtility.RectangleContainsScreenPoint」都有人可能會發現你的問題。 – Programmer

+0

我使用代碼 –

+0

更新了帖子也許是因爲您試圖獲得「渲染器」而不是「CanvasRenderer」? –

回答

2

列表CanvasRenders沒有bounds成員變量。但是,只需使用RectTransform.rect成員變量即可完成您的任務,因爲我們可以通過此方式獲取矩形的寬度和高度。我的腳本下面假設你的畫布元素被錨定到你畫布的中心。當鼠標位於腳本所在元素的內部時,它會打印出「TRUE」。

void Update() 
{ 
    Vector2 point = Input.mousePosition - new Vector3(Screen.width/2, Screen.height/2); // convert pixel coords to canvas coords 
    Debug.Log(IsPointInRT(point, this.GetComponent<RectTransform>())); 
} 

bool IsPointInRT(Vector2 point, RectTransform rt) 
{ 
    // Get the rectangular bounding box of your UI element 
    Rect rect = rt.rect; 

    // Get the left, right, top, and bottom boundaries of the rect 
    float leftSide = rt.anchoredPosition.x - rect.width/2; 
    float rightSide = rt.anchoredPosition.x + rect.width/2; 
    float topSide = rt.anchoredPosition.y + rect.height/2; 
    float bottomSide = rt.anchoredPosition.y - rect.height/2; 

    //Debug.Log(leftSide + ", " + rightSide + ", " + topSide + ", " + bottomSide); 

    // Check to see if the point is in the calculated bounds 
    if (point.x >= leftSide && 
     point.x <= rightSide && 
     point.y >= bottomSide && 
     point.y <= topSide) 
    { 
     return true; 
    } 
    return false; 
} 
+0

謝謝,這幫了我! –