怎么实现无遮罩屏蔽某些按钮的点击事件

给需要能点击的UI控件上绑定一个实现了ICanvasRaycastFilter接口的组件,在方法IsRaycastLocationValid中判断当前点击的位置是否符合响应事件的条件

附三段代码示例:

public class NewBehaviourScript : MonoBehaviour,ICanvasRaycastFilter
{
    public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
    {
        var mousePos = eventCamera.WorldToScreenPoint(transform.position);
        if (Vector2.Distance(mousePos,sp)<3)
        {
            return true;
        }

        return false;
    }
}
 public class GuideMaskComponent : MonoBehaviour, ICanvasRaycastFilter
    {
        private RectTransform holeTf;
        public GameObject Text;

        public void ShowText(float delay)
        {
            StartCoroutine(StartShowText(delay));
        }

        IEnumerator StartShowText(float delay)
        {
            yield return new WaitForSeconds(delay);
            Text.SetActive(true);
        }

        public void SetHoleTransform(Transform tf)
        {
            holeTf = tf as RectTransform;
        }

        public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
        {
            if (holeTf != null)
            {
                if (RectTransformUtility.RectangleContainsScreenPoint(holeTf, sp, eventCamera))
                    return false;

            }
            return true;
        }
    }
using UnityEngine;
 
public class CircleGraphic : MonoBehaviour, ICanvasRaycastFilter
{
   public float Radius;
   private RectTransform rectTransform;
 
   void Start()
   {
     rectTransform = this.GetComponent<RectTransform>();
   }
 
   public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
   {
     Vector2 screenPoint = eventCamera.WorldToScreenPoint(rectTransform.position);
     return (Vector2.Distance(sp, screenPoint) < Radius);
   }
}

https://forum.unity.com/threads/non-rectangular-button-with-adequate-input-detection-area.263537/

https://www.reddit.com/r/Unity3D/comments/4v2pw9/polygon_raycast_target_for_ui_buttonsitems/

发布了17 篇原创文章 · 获赞 2 · 访问量 6万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 创作都市 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览