【问题标题】:Unity Recttransform contains pointunity Recttransform 包含点
【发布时间】:2021-02-19 01:43:07
【问题描述】:

有没有办法检查 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));
}

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

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

这个方法总是返回false

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

lines 是 GameObjects 的列表

【问题讨论】:

  • 请包含您尝试过的代码。你的问题只是一个函数。放置不起作用的代码。 Bounds.ContainsRectTransformUtility.RectangleContainsScreenPoint 可能会有人发现您的问题。
  • 我用代码更新了帖子
  • 可能是因为您试图获取“渲染器”而不是“CanvasRenderer”?
  • 我尝试获取 CanvasRenderer 但它不起作用
  • 我更新了帖子

标签: c# unity3d


【解决方案1】:

CanvasRenders 没有bounds 成员变量。但是,您的任务可以仅使用RectTransform.rect 成员变量来完成,因为我们可以通过这种方式获得矩形的宽度和高度。下面的脚本假设您的画布元素锚定在画布的中心。当您的鼠标位于脚本附加到的元素内时,它会打印“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;
}

【讨论】:

  • 谢谢,这对我有帮助!
【解决方案2】:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-18
  • 1970-01-01
  • 2021-08-13
  • 1970-01-01
相关资源
最近更新 更多