zoukankan      html  css  js  c++  java
  • UGUI之不规则按钮的响应区域

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

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

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

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

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

    3.编辑Polygon的区域即可。

     1 using UnityEngine;
     2 using System.Collections;
     3 using UnityEngine.UI;
     4 #if UNITY_EDITOR
     5 using UnityEditor;
     6 #endif
     7 [RequireComponent(typeof(PolygonCollider2D))]
     8 public class UIPolygon : Image 
     9 {
    10     private PolygonCollider2D _polygon = null;
    11     private PolygonCollider2D polygon 
    12     {
    13         get{
    14             if(_polygon == null )
    15                 _polygon = GetComponent<PolygonCollider2D>();
    16             return _polygon;
    17         }
    18     }
    19     protected UIPolygon()
    20     {
    21         useLegacyMeshGeneration = true;
    22     }
    23     protected override void OnPopulateMesh(VertexHelper vh)
    24     {
    25         vh.Clear();
    26     }
    27     public override bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
    28     {
    29         return polygon.OverlapPoint( eventCamera.ScreenToWorldPoint(screenPoint));
    30     }
    31  
    32  #if UNITY_EDITOR
    33     protected override void Reset()
    34     {
    35         base.Reset();
    36         transform.localPosition = Vector3.zero; 
    37         float w = (rectTransform.sizeDelta.x *0.5f) + 0.1f;
    38         float h = (rectTransform.sizeDelta.y*0.5f)  + 0.1f;
    39         polygon.points = new Vector2[] 
    40         {
    41             new Vector2(-w,-h),
    42             new Vector2(w,-h),
    43             new Vector2(w,h),
    44             new Vector2(-w,h)
    45           };
    46     }
    47 #endif
    48 }
    49 #if UNITY_EDITOR
    50 [CustomEditor(typeof(UIPolygon), true)]
    51 public class UIPolygonInspector : Editor
    52 {
    53     public override void OnInspectorGUI()
    54     {
    55     }
    56 }
    57 #endif

    原文链接: http://www.xuanyusong.com/archives/3492

  • 相关阅读:
    BZOJ3578:GTY的人类基因组计划2(集合hash,STL)
    【BZOJ 1022】 [SHOI2008]小约翰的游戏John
    【BZOJ 1295】 [SCOI2009]最长距离
    【BZOJ 1103】 [POI2007]大都市meg
    【BZOJ 3172】 [Tjoi2013]单词
    【BZOJ 1067】 [SCOI2007]降雨量
    【BZOJ 1491】 [NOI2007]社交网络
    【BZOJ 1087】[SCOI2005]互不侵犯King
    【BZOJ 1009】 [HNOI2008]GT考试
    【BZOJ 1053】[HAOI2007]反素数ant
  • 原文地址:https://www.cnblogs.com/AaronBlogs/p/7428951.html
Copyright © 2011-2022 走看看