本文介绍了检查 UI 元素/RectTransform 是否重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何检查 Unity Canvas 上的两个 UI 面板是否相互重叠.
I'd like to know how I check whether two UI Panels on my Unity Canvas are overlapping each other.
目前我通过比较画布元素 Rects
Currently I am doing this by comparing the canvas elements Rects
画布设置
- 渲染模式:屏幕空间 - 相机
- 完美像素:[是]
- 渲染相机:主相机
- 平面距离:100
- 排序层:默认
- 层中的顺序:0
画布缩放器设置
- 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);
}
发生了什么
'Overlapping' bool 立即变为 true.
'Overlapping' bool instantly changes to true.
矩形一返回为(示例)
X -7.5,Y 2.5宽 98.5,高 164.1667
X -7.5, Y 2.5W 98.5, H 164.1667
推荐答案
将 RectTransform
转换为 Rect
然后检查它是否重叠.
Convert the RectTransform
to Rect
then check if it overlaps.
这是一个可以做到这一点的简单函数:
Here is a simple function that can do that:
bool rectOverlaps(RectTransform rectTrans1, RectTransform rectTrans2)
{
Rect rect1 = new Rect(rectTrans1.localPosition.x, rectTrans1.localPosition.y, rectTrans1.rect.width, rectTrans1.rect.height);
Rect rect2 = new Rect(rectTrans2.localPosition.x, rectTrans2.localPosition.y, rectTrans2.rect.width, rectTrans2.rect.height);
return rect1.Overlaps(rect2);
}
用法:
public RectTransform uiRect1;
public RectTransform uiRect2;
void Update()
{
if (rectOverlaps(uiRect1, uiRect2))
{
Debug.Log("Overlaps");
}else
{
Debug.Log("Does not Overlap");
}
}
更好的是,让它成为一个扩展方法:
Even better, make it an extension method:
public static class ExtensionMethod
{
public static bool rectOverlaps(this RectTransform rectTrans1, RectTransform rectTrans2)
{
Rect rect1 = new Rect(rectTrans1.localPosition.x, rectTrans1.localPosition.y, rectTrans1.rect.width, rectTrans1.rect.height);
Rect rect2 = new Rect(rectTrans2.localPosition.x, rectTrans2.localPosition.y, rectTrans2.rect.width, rectTrans2.rect.height);
return rect1.Overlaps(rect2);
}
}
现在你可以了
public RectTransform uiRect1;
public RectTransform uiRect2;
void Update()
{
if (uiRect1.rectOverlaps(uiRect2))
{
}
//OR
if (uiRect2.rectOverlaps(uiRect1))
{
}
}
这篇关于检查 UI 元素/RectTransform 是否重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!