Unity UGUI不规则响应区域

需求说明

有时候需要点击图片的某一部分,而这一部分又是不规则的图形

解决方案

做法其实很简单,添加PolygonCollider2D组件,点击EditCollider,自己拖动成想要的图案,最后重写射线检测的方法就大功告成了

//***********************************************************
// 描述:不规则图形精确点击
// 作者:花花蔡 
// 创建时间:2020-05-21 14:43:08
// 版 本:1.0
//***********************************************************
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CustomImage : Image
{
    PolygonCollider2D _polygon;
    PolygonCollider2D Polgon
    {
        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);
    }

}
  • 最后贴上Editor脚本用于在直接创建不规则点击的Prefab
//***********************************************************
// 描述:UGUI不规则响应区域
// 作者:花花蔡 
// 创建时间:2020-05-21 14:42:43
// 版 本:1.0
//***********************************************************
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

public class CustomImageEditor : Editor
{
    private const int UI_LAYER = 5;

    [MenuItem("GameObject/UI/CustomImageBtn", priority = 4)]
    private static void AddImage()
    {

        Transform canvasTrans = GetCanvasTrans();

        Transform image = AddCustomImage();

        if (Selection.activeGameObject!= null && Selection.activeGameObject.layer == UI_LAYER)
        {
            image.SetParent(Selection.activeGameObject.transform);
        }
        else
        {
            image.SetParent(canvasTrans);
        }
       
        image.localPosition = Vector3.zero;
    }

    private static Transform GetCanvasTrans()
    {
        Canvas canvas = GameObject.FindObjectOfType<Canvas>();
        if (canvas == null)
        {
            GameObject canvasObj = new GameObject("Canvas");
            SetLayer(canvasObj);
            canvasObj.AddComponent<RectTransform>();
            canvasObj.AddComponent<Canvas>().renderMode = RenderMode.ScreenSpaceOverlay;
            canvasObj.AddComponent<CanvasScaler>();
            canvasObj.AddComponent<GraphicRaycaster>();
            return canvasObj.transform;
        }
        else
        {
            return canvas.transform;
        }
    }

    private static Transform AddCustomImage()
    {
        GameObject image = new GameObject("CustomImageBtn");
        SetLayer(image);
        image.AddComponent<RectTransform>();
        image.AddComponent<PolygonCollider2D>();
        image.AddComponent<CustomImage>();
        image.AddComponent<Button>();
        return image.transform;
    }

    private static void SetLayer(GameObject ui)
    {
        ui.layer = UI_LAYER;
    }
}

你可能感兴趣的:(Unity,UGUI)