UGUI點擊不規則的圖片

在Unity中開發中難免會遇到不規則圖片的點擊的需求,看網上主要的做法有兩種,一種是給圖片添加polygon Collider來添加不規則的形狀。一種是根據圖片的alpha來判斷。我這裏找了一個記錄下來。

首先找到不規則的圖片,打開圖片的可讀可寫:

勾選Read/Write Enbale之後,

unity的image提供了一個alphaHitTestMinimumThreshold的屬性,這個屬性提供了一個限制鼠標檢測的一個alpha值,也就是說,當我們GetComponent().alphaHitTestMinimumThreshold = 0.1f;的時候(0.1是自定義的值),點擊圖片上像素的alpha值小於0.1的區域,程序就不會有響應

看代碼:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(RectTransform))]
[RequireComponent(typeof(Image))]
public class BtnController : MonoBehaviour
{
    [Tooltip("設定Sprite響應的Alpha闕值")]
    [Range(0,0.8f)]
    public float alphaThreshold = 0.5f;

    private void Awake()
    {
        var image = transform.GetComponent<Image>();
        if (null != image)
        {
            image.alphaHitTestMinimumThreshold = alphaThreshold;
        }
    }

    public void OnClick()
    {
        Debug.Log("點擊相應");
    }
}

 

發佈了62 篇原創文章 · 獲贊 53 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章