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