Unity2D-UGUI多边形检测

PolygonCollider2D

PolygonCollider2D是Unity用于多边形检测的组件,可以进行不规则UI、2d对象的射线检测。

为UI对象添加如下脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class CustomImage : Image
{
private PolygonCollider2D _polygon;

private PolygonCollider2D Polygon
{
get
{
if (_polygon == null)
_polygon = GetComponent<PolygonCollider2D>();

return _polygon;
}
}


public override bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
{
Vector3 point;
RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, screenPoint, eventCamera, out point);
return Polygon.OverlapPoint(point);
}
}

并将Button组件的source设置为上面的脚本即可。

参考文章

  1. Unity UGUI学习系列(二) —— PolygonCollider2D实现不规则碰撞范围_千喜的博客-CSDN博客