解决 scale、pivot 改变后 检测不准确问题
using UnityEngine;
public static class ExpTool
{
static Rect rect = new Rect();
static float x, y, width, height;
static Vector2 center;
public static Rect GetRect(this RectTransform self, float offsetScale = 1f)
{
width = Abs(self.rect.width * self.localScale.x * offsetScale);
height = Abs(self.rect.height * self.localScale.y * offsetScale);
center = self.anchoredPosition;
x = -width * self.pivot.x + center.x;
y = -height * self.pivot.y + center.y;
SetNewRectData();
return rect;
}
static void SetNewRectData()
{
rect.x = x;
rect.y = y;
rect.width = width;
rect.height = height;
}
public static float Abs(float val)
{
return val > 0 ? val : -val;
}
/// <summary>
/// 覆盖检测
/// </summary>
/// <param name="self"></param>
/// <param name="other"></param>
/// <param name="otherOffsetScale">自定义检测大小</param>
/// <returns></returns>
public static bool OverLaps(this RectTransform self, RectTransform other, float otherOffsetScale = 1f)
{
return self.GetRect().Overlaps(other.GetRect(otherOffsetScale));
}
}
/// <summary>
/// 改变pivot位置
/// </summary>
/// <param name="self"></param>
/// <param name="toPivot"></param>
public static void ChangePivot(this RectTransform self, Vector2 toPivot)
{
width = Abs(self.rect.width * self.localScale.x);
height = Abs(self.rect.height * self.localScale.y);
center = self.anchoredPosition;
x = -width * (self.pivot.x - toPivot.x) + center.x;
y = -height * (self.pivot.y - toPivot.y) + center.y;
self.pivot = toPivot;
self.anchoredPosition = new Vector2(x, y);
}
/// <summary>
/// 获取到相机垂直距离
/// </summary>
/// <param name="self"></param>
/// <param name="camera"></param>
/// <returns></returns>
public static float ToCameraDistance(this RectTransform self, Camera camera)
{
var plane = new Plane(camera.transform.forward, camera.transform.position);
return plane.GetDistanceToPoint(self.position);
}
参考: