我想知道如何检查 Unity Canvas 上的两个 UI 面板是否相互重叠。
目前我正在通过比较 Canvas 元素矩形来做到这一点
Canvas 设置
- 渲染模式:屏幕空间 - 相机
- 像素完美:[是]
- 渲染相机:主相机
- 平面距离:100
- 排序层:默认
- 层顺序:0
Canvas 缩放器设置
- UI 缩放模式:恒定像素大小
- 比例因子:1
- 每单位引用像素:100
我用来检查的代码
[Header("Check For Overlap")]
public RectTransform PlayerBar;
public RectTransform LeftBar;
public Rect RectOne;
public Rect RectTwo;
public bool overlapping;
//Check if the two canvas element Rects overlap each other
public void CheckForOverlap()
{
overlapping = false;
// Convert Canvas RectTransforms to World Rects
RectOne = GetWorldRect(LeftBar);
RectTwo = GetWorldRect(PlayerBar);
if (RectOne.Overlaps(RectTwo))
{
overlapping = true;
}
}
public Rect GetWorldRect(RectTransform rt)
{
// Get World corners, take top left
Vector3[] corners = new Vector3[4];
rt.GetWorldCorners(corners);
Vector3 topLeft = corners[0];
// Rect Size ... I'm not sure if this is working correctly?
Vector2 size = new Vector2(rt.rect.size.x, rt.rect.size.y);
return new Rect(topLeft, size);
}
发生了什么
“重叠” bool 值立即更改为 true。
矩形返回为(示例)
X -7.5,Y 2.5 宽98.5,高164.1667
最佳答案
更新版本考虑了 rectTransform 的比例。
public static class RectTransformExtensions
{
public static bool Overlaps(this RectTransform a, RectTransform b) {
return a.WorldRect().Overlaps(b.WorldRect());
}
public static bool Overlaps(this RectTransform a, RectTransform b, bool allowInverse) {
return a.WorldRect().Overlaps(b.WorldRect(), allowInverse);
}
public static Rect WorldRect(this RectTransform rectTransform) {
Vector2 sizeDelta = rectTransform.sizeDelta;
float rectTransformWidth = sizeDelta.x * rectTransform.lossyScale.x;
float rectTransformHeight = sizeDelta.y * rectTransform.lossyScale.y;
Vector3 position = rectTransform.position;
return new Rect(position.x - rectTransformWidth / 2f, position.y - rectTransformHeight / 2f, rectTransformWidth, rectTransformHeight);
}
}
关于c# - 检查 UI 元素/RectTransform 是否重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42043017/