伊景轩

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

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

应用场景:

1.引导挖洞

2.ui事件触发,并且不影响下面的其他控件的事件响应

附三段代码示例:

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/

posted on 2020-01-16 18:24  伊景轩  阅读(238)  评论(0编辑  收藏  举报

导航