Unity 中不规则图片的点击策略

Polygon Collider 2D 组件的使用 -> Edit Collider 

IsRaycastLocationValid 重写

using UnityEngine;
using UnityEngine.UI;

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)
    {
        // 3维向量
        Vector3 point;

        // 屏幕点转换到世界坐标
        RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, screenPoint, eventCamera, out point);

        // 多边形PolygonCollider2D 的基类 Collider2D 有一个OverlapPoint方法 将点传进去 就能判断是否与在图形上
        return Polygon.OverlapPoint(point);
    }
}

 

posted @ 2021-04-29 22:25  一个新星的诞生  阅读(35)  评论(0)    收藏  举报