public bool ICanvasRaycastFilter.IsRaycastLocationValid(Vector2 sp,Camera eventCamera);
在指定摄像机eventCamera中,屏幕坐标sp是否可以点击到this.RectTransform。
public static bool RectTransformUtility.RectangleContainsScreenPoint(RectTransform rect,Vector2 screenPoint,Camera cam,Vector4 offset);
在指定摄像机cam中,屏幕坐标screenPoint是否在rect的范围内。判定区域偏移offset: x:左偏移;y:下偏移;z:右偏移;w:上偏移; 正数向里偏移,负数向外偏移。
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Image))]
public class TestImage : MonoBehaviour, ICanvasRaycastFilter
{
//在指定摄像机eventCamera中,屏幕坐标sp是否可以点击到this.RectTransform
//public bool ICanvasRaycastFilter.IsRaycastLocationValid(Vector2 sp,Camera eventCamera);
//在指定摄像机cam中,屏幕坐标screenPoint是否在rect的范围内
//判定区域偏移offset: x:左偏移;y:下偏移;z:右偏移;w:上偏移; 正数向里偏移,负数向外偏移;
//public static bool RectTransformUtility.RectangleContainsScreenPoint(RectTransform rect,Vector2 screenPoint,Camera cam,Vector4 offset);
//例1: 使用rectangleOffset,可以点击区域为Image四条边往里偏移10之后围成的矩形
public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
{
Vector4 rectangleOffset = new Vector4(10,10,10,10);
return RectTransformUtility.RectangleContainsScreenPoint(transform as RectTransform,sp,eventCamera,rectangleOffset);
}
//例2: 此处可以时任意RectTransform(比如,利用子物体标记父物体可点击区域,与子物体重叠部分可以点击,其余部分不可点击)
public bool IsRaycastLocationValid(Vector2 sp,Camera eventCamera)
{
RectTransform rectTransform = transform.GetChild(0) as RectTransform;
return RectTransformUtility.RectangleContainsScreenPoint(rectTransform,sp,eventCamera);
}
//例3: 可点击区域是 以Image自身为圆心,radius半径形成的圆形
public bool IsRaycastLocationValid(Vector2 sp,Camera eventCamera)
{
Vector2 selfPos = RectTransformUtility.WorldToScreenPoint(eventCamera,transform.position);
float radius = 100;
return (selfPos - sp).sqrMagnitude <= radius * radius;
}
}