unity3d Unity矩形变换包含点

qyswt5oh  于 2023-01-21  发布在  其他
关注(0)|答案(3)|浏览(197)

有没有办法检查矩形变换是否包含点?提前感谢。我尝试了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));
}

这样我会收到一个错误“There is no renderer attached to the object”,但我已经将CanvasRenderer附加到它了。

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

此方法始终返回false

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

lines是游戏对象的列表

wpx232ag

wpx232ag1#

CanvasRenders没有bounds成员变量。但是,您的任务可以只使用RectTransform.rect成员变量来完成,因为我们可以通过这种方式获得矩形的宽度和高度。下面的脚本假设您的canvas元素锚定在Canvas的中心。当您的鼠标位于脚本所连接的元素内部时,它将打印“TRUE”。

void Update()
{
    // convert pixel coords to canvas coords
    Vector2 point = Input.mousePosition - new Vector2(Screen.width / 2, Screen.height / 2); 
    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;
}
vhmi4jdf

vhmi4jdf2#

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

pu3pd22g

pu3pd22g3#

对于UI对象container,您可以只使用其rect的Contains方法(带有本地位置):

container.rect.Contains(localPosition);

如果更喜欢使用世界位置,只需将其转换为局部空间:

container.rect.Contains(container.InverseTransformPoint(worldPosition));

相关问题