Unity(三十四):不规则区域点击事件

效果

在这里插入图片描述

脚本

游戏对象组件 Image PolygonCollider2D

  • 方式一:
    using UnityEngine;
    using UnityEngine.EventSystems;
    using UnityEngine.UI;
    
    [RequireComponent(typeof(PolygonCollider2D))]
    public class PolygonColliderPointerHandler : Image, IPointerClickHandler
    {
          
          
        private PolygonCollider2D _polygon;
    
        private PolygonCollider2D Polygon
        {
          
          
            get
            {
          
          
                if (_polygon == null) _polygon = GetComponent<PolygonCollider2D>();
                return _polygon;
            }
        }
    
        // 判断是否在区域内
        public override bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
        {
          
          
            RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, screenPoint, eventCamera,
                out Vector3 point);
            return Polygon.OverlapPoint(point); // 判断点击位置是否在区域内
        }
    
        public void OnPointerClick(PointerEventData eventData)
        {
          
          
            Debug.Log("不规则区域点击事件~~~");
        }
    }
    
  • 方式二:
    using UnityEngine;
    using UnityEngine.EventSystems;
    
    [RequireComponent(typeof(PolygonCollider2D))]
    public class PolygonColliderPointerHandler : MonoBehaviour, IPointerClickHandler
    {
          
          
        private PolygonCollider2D _polygon;
    
        private void Awake()
        {
          
          
            _polygon = GetComponent<PolygonCollider2D>();
        }
    
        public void OnPointerClick(PointerEventData eventData)
        {
          
          
            if (_polygon.OverlapPoint(eventData.position))
            {
          
          
                Debug.Log("不规则区域点击事件~~~");
            }
        }
    }
    

猜你喜欢

转载自blog.csdn.net/weixin_43526371/article/details/123044770