2016-11-12 234 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

谢谢,这帮了我! –