本文介绍了检查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);
}
会发生什么
重叠"布尔立即变为true.
'Overlapping' bool instantly changes to true.
Rect One返回(示例)
The Rect One returns as (example)
X -7.5,Y 2.5W 98.5,H 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是否重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!