Unity Recttransform包含点

时间:2016-11-12 18:30:16

标签: c# unity3d

有没有办法检查Rect变换是否包含点?提前致谢。我试过Bounds.Contains()和RectTransformUtility.RectangleContainsScreenPoint(),但那对我没有帮助

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

这样我就会出现错误&#34;没有渲染器附加到对象&#34;但我已经将CanvasRenderer附加到它上面了。

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

此方法始终返回false

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

lines是GameObjects的列表

enter image description here

2 个答案:

答案 0 :(得分:4)

CanvasRenders没有bounds成员变量。但是,您的任务只需使用RectTransform.rect成员变量即可完成,因为我们可以以这种方式获得矩形的宽度和高度。我的脚本假设您的canvas元素锚定到Canvas的中心。它打印&#34; TRUE&#34;当您的鼠标位于脚本所附加的元素内部时。

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

答案 1 :(得分:0)

您需要将UI Camera作为RectTransformUtility.RectangleContainsScreenPoint的第三个参数提供,以使其正常工作