首页 >Unity3D频道 >【UGUI研究院】 > UGUI研究院之不规则按钮的响应区域(十四)
2015
05-15

UGUI研究院之不规则按钮的响应区域(十四)

接上一篇文章 UGUI研究院之忽略UI被拦截事件(十三)

比如一些不规则按钮最好可以设置它的响应区域。如下图所示,用Polygon Collider2D组件圈出精灵响应事件的区域。

Snip20150515_2

 

注意 IsRaycastLocationValid 的判断区域是RectTransform的区域。 如果 polygon Collider编辑出来的区域大于RectTransform , 必须调节RectTransform的区域。

例子:比如想把按钮的点击区域改成不规则的。

1.把按钮的image的RaycastTarget关闭勾选

2.在子节点创建新的gameObject挂上下面UIPolygon脚本。

3.编辑Polygon的区域即可。

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
#if UNITY_EDITOR
using UnityEditor;
#endif
[RequireComponent(typeof(PolygonCollider2D))]
public class UIPolygon : Image 
{
    private PolygonCollider2D _polygon = null;
    private PolygonCollider2D polygon 
    {
        get{
            if(_polygon == null )
                _polygon = GetComponent<PolygonCollider2D>();
            return _polygon;
        }
    }
    protected UIPolygon()
    {
        useLegacyMeshGeneration = true;
    }
    protected override void OnPopulateMesh(VertexHelper vh)
    {
        vh.Clear();
    }
    public override bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
    {
        return polygon.OverlapPoint( eventCamera.ScreenToWorldPoint(screenPoint));
    }

 #if UNITY_EDITOR
    protected override void Reset()
    {
        base.Reset();
        transform.localPosition = Vector3.zero; 
        float w = (rectTransform.sizeDelta.x *0.5f) + 0.1f;
        float h = (rectTransform.sizeDelta.y*0.5f)  + 0.1f;
        polygon.points = new Vector2[] 
        {
            new Vector2(-w,-h),
            new Vector2(w,-h),
            new Vector2(w,h),
            new Vector2(-w,h)
          };
    }
#endif
}
#if UNITY_EDITOR
[CustomEditor(typeof(UIPolygon), true)]
public class UIPolygonInspector : Editor
{
    public override void OnInspectorGUI()
    {
    }
}
#endif

 

最后编辑:
作者:雨松MOMO
专注移动互联网,Unity3D游戏开发
捐 赠写博客不易,如果您想请我喝一杯星巴克的话?就进来看吧!

UGUI研究院之不规则按钮的响应区域(十四)》有 39 条评论

  1. Newman说:

    请问大佬,如果多个不规则区域,比如地图的各个国家,那么RectTransform就会互相重叠,响应点击事件的时候就只会判断和响应最上层的RectTransform,如果没点击到最上层的polygon,也不会继续判断下一层的polygon了,请问这个问题怎么解决比较好呢?

留下一个回复

你的email不会被公开。 必填项已用 * 标注。