Rect.OverLaps() 改进

解决 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);
    }

参考:

https://www.cnblogs.com/w199753/p/12599099.html

https://blog.csdn.net/danteshenqu/article/details/108664491

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值