0
点赞
收藏
分享

微信扫一扫

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


效果

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

脚本

游戏对象组件 ​​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("不规则区域点击事件~~~");
}
}
}


举报

相关推荐

0 条评论