Unity Recttransform包含点

Ale*_*RED 1 c# unity-game-engine

有没有一种方法可以检查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));
}
Run Code Online (Sandbox Code Playgroud)

这样我有一个错误“没有渲染器附加到对象”,但是我已经将CanvasRenderer附加到它了。

RectTransformUtility.RectangleContainsScreenPoint(gameObj.GetComponent<RectTransform>(), coords);
Run Code Online (Sandbox Code Playgroud)

此方法总是返回false

if (AreCoordsWithinUiObject(point, lines[i]))
{
    print("contains");
}
Run Code Online (Sandbox Code Playgroud)

行是GameObjects的列表

在此处输入图片说明

bpg*_*eck 5

CanvasRenders没有bounds成员变量。但是,仅通过RectTransform.rect成员变量即可完成您的任务,因为我们可以通过这种方式获取矩形的宽度和高度。下面的脚本假定您的canvas元素锚定在Canvas的中心。当您的鼠标位于脚本所附加的元素内部时,它将输出“ 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;
}
Run Code Online (Sandbox Code Playgroud)