gpt4 book ai didi

c# - unity Recttransform 包含点

转载 作者:太空宇宙 更新时间:2023-11-03 19:50:03 30 4
gpt4 key购买 nike

有没有办法检查 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 是一个游戏对象列表

enter image description here

最佳答案

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

关于c# - unity Recttransform 包含点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40566250/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com