找出对象的框实际 4 条边缩放到 screen/camera 大小(Unity 2D)

Find out an object's box actual 4 edges scaled to the screen/camera size (Unity 2D)

我正在编写一个函数来确定一个二维对象是否完全位于另一个对象内部。 我这样做是通过获取对象的位置,然后使用该位置及其大小,计算对象的边缘位置,然后使用 Camera.main.pixelRect.Contains 进行检查。这是我当前的代码:

 // get the center of the object
 Vector2 pos = Camera.main.WorldToScreenPoint(card.transform.position);

 // get the bounding box
 var rect = image.transform.rect;

 var topLeft = new Vector2(pos.x - (rect.width / 2), pos.y - (rect.height / 2);


return Camera.main.pixelRect.Contains(topLeft);

我的问题是,作为 Unity 的新手,测量值不匹配。我很困惑当对象随屏幕尺寸缩放时,我会得到图像的实际宽度并且计算错误。

我还通过以下方式测试了是否正确:

rect = GetComponent<RectTransform>().rect;

谁能帮我解决这个问题?

Ps:如果有更好的方法来检查二维对象何时完全位于另一个对象内部,我也会接受。

正如 Draco18s 指出的那样,您将 pos 转换为屏幕 space 而不是 rect.

如果您查看 WorldToScreenPoint() 的 Unity API 文档 它说

Transforms position from world space into screen space. Screenspace is defined in pixels.

transform.position returns

The position of the transform in world space.

你遇到的问题是将屏幕 space(以像素为单位)与世界 space 相结合,这是完全不同的。

因为您正在使用 pixelRect,我建议更改 var rect = image.transform.rect; 成为 var rect = Camera.main.WorldToScreenPoint(image.transform.position);

当然,您还必须以类似的方式检查其他角,如果所有 4 个角 return 都为真,则对象在另一个角内。