c# - 检查 UI 元素/RectTransform 是否重叠

标签 c# user-interface unity-game-engine rect

我想知道如何检查 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/

相关文章:

c# - HttpClient PostAsync 无效的发布格式

c# - PagedList.Mvc 在 MvcHtmlString 上抛出异常

android - 在 Unity 移动应用程序中获取加载的 AdMob 广告目标 URL

java - 应用程序无法关闭(Glass、Unity3d)

python - 从 python Gtk 列表中选择一个选项并将其存储在变量中

javascript - Unity Javascript 文件在 Xcode 中打开

c# - 在 ASP.NET Web 窗体中管理长时间运行的任务的策略

c# - 如何使用 ASP.Net C# 更改 CKEditor 的输入语言

java - jlist 由 arrayList 填充。单击项目时,信息应显示在 jTextArea 中。但它做了两次

python - 属性错误: 'module' object has no attribute 'tk'