UGUI image 圆形响应区域

需求:圆形外观按钮,圆形区域外不希望被响应。
问题:unity image 响应区域为方形范围,无法支持圆形点击限制。
处理方案:自定义 CircleEventImage 继承自 Image 复写IsRaycastLocationValid 函数,计算点击点是否处于圆形区域内。

初始方案:CircleCollider2D 检测点击点是否再 圆形区域。代码如下:

public class CircleEventImage : Image
{
    CircleCollider2D m_pCollider;
    RectTransform m_pRTran;
    protected override void Start()
    {
        base.Start();
        m_pRTran = GetComponent<RectTransform>();
        m_pCollider = gameObject.GetComponent<CircleCollider2D>();
    }

    public override bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
    {
        bool bRayUI = base.IsRaycastLocationValid(screenPoint, eventCamera);
        if (bRayUI && m_pCollider != null)
        {
            bRayUI = m_pCollider.OverlapPoint(screenPoint);
        }
        return bRayUI;
    }
}

遇到新问题:由于Transform 位置,对其方是不对导致 OverlapPoint 判断结果不准确。
添加位置转换逻辑,复写的IsRaycastLocationValid方法代码如下:

    public override bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
    {
        bool bRayUI = base.IsRaycastLocationValid(screenPoint, eventCamera);
        if (bRayUI && m_pCollider != null)
        {
            Vector3 localPos;
            //RectTransformUtility.ScreenPointToLocalPointInRectangle(m_pRTran, screenPoint, eventCamera, out localPos);
            RectTransformUtility.ScreenPointToWorldPointInRectangle(m_pRTran, screenPoint, eventCamera, out localPos);
            //Debug.Log("Screen point:" + screenPoint + " bound:" + m_pCollider.bounds);
            bRayUI = m_pCollider.OverlapPoint(localPos);
        }
        return bRayUI;
    }

功能上基本能完成需求,但是又遇到新的问题 该子类无法想image类一样在Inspector面板设置如下内容在这里插入图片描述可以通过如下方式指定自定义面板显示。这里我们使用ImageEditor.

#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.UI;
[CustomEditor(typeof(ImageEditor))]
#endif
public class CircleEventImage : Image
{

注意需要将
using UnityEditor;
using UnityEditor.UI
限定在 UNITY_EDITOR 模式下,否则打包可能会出错。
同时,如果使用了自定义的Editor 需要将文件目录放置到 Editor 文件夹或其子文件夹下。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值