本系列文章是學(xué)習(xí)siki學(xué)院UGUI整體解決方案-案例篇筆記
GitHub地址:https://github.com/BlueMonk1107/UGUISolution
本文實(shí)現(xiàn)的是在image點(diǎn)擊不規(guī)則碰撞區(qū)域響應(yīng)事件,效果如下 :
一.添加PolygonCollider2D組件,設(shè)置碰撞范圍
可以選擇Editor Collider直接拖動(dòng),也可以直接修改point
二.新建腳本,重寫(xiě)IsRaycastLocationValid
具體代碼如下 :
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并添加響應(yīng)事件
測(cè)試代碼如下 :
public void MouseDown() {
Debug.Log("aaa");
}
這樣點(diǎn)擊臉部區(qū)域時(shí)會(huì)輸出aaa,點(diǎn)擊圖片的其他區(qū)域不會(huì)輸出