UGUI_不规则按钮的响应区域

1.Polygon Collider2D组件圈出精灵响应事件的区域。

 

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

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

1.把按钮的imageRaycastTarget关闭勾选

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

3.编辑Polygon的区域即可。

 

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

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

   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LetsonH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值