UGUI 不规则检测区域

UGUI 的RayCast 不规则检测区域

第一种方式:不推荐
开启Texture的Read/write

获取鼠标位置的像素的透明度,当透明度低于阀值,拦截,但是开启图片的读写功能,图片占用内存会增大,且无法合并到图集,不推荐使用
void Start()
{
	GetComponent<Image>().alphaHitTestMinimumThreshold = 0.1f;
}

第二种方式:推荐使用
重写Image的 IsRaycastLocationValid(vector2 screenPoint,Camera eventCamera);

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class IrregularUIClick : Image
{
    private PolygonCollider2D _polygon;
    public PolygonCollider2D Polygon
    {
        get
        {
            if (_polygon == null)
                _polygon = GetComponent<PolygonCollider2D>();
            return _polygon;
        }
    }
    public override bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
    {
        RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, screenPoint, eventCamera, out Vector3 worldPoint);
        return Polygon.OverlapPoint(worldPoint);
    }
}

添加 PolygonCollider2D组件,经过实践,发现 挂了 Image 和 PolygonCollider2D 并不能正确的生成碰撞区域,

解决方法: 再挂上 Spirte Render组件,点击PolygonCollider2D 的Reset ,可以生成正确的碰撞体,
然后再删掉 Spirte Render组件 就是了

如果遇到生成的碰撞体形状是正确的,但比实际的图片小100倍,使用下面的脚本,点reset即可

using UnityEngine;

public class UGUIPolygonCollider : MonoBehaviour
{
    PolygonCollider2D poly2D;
    Vector2[] pos_save;//存放PolygonCollider2D的Point点位
    public float identity = 100f;
    void Reset()
    {
        poly2D = GetComponent<PolygonCollider2D>();
        SetPos();
    }
    void SetPos()
    {
        pos_save = poly2D.GetPath(0);
        for (int i = 0; i < pos_save.Length; i++)
        {
            pos_save[i] = pos_save[i] * identity;
        }
        poly2D.SetPath(0, pos_save);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值