using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.IO;
[DisallowMultipleComponent]
[RequireComponent(typeof(Image))]
[ExecuteInEditMode]
public class ImageRaycastFilter : MonoBehaviour, ICanvasRaycastFilter
{
public bool reversed;
private Image image;
void OnEnable()
{
image = GetComponent<Image>();
image.type = Image.Type.Simple;
}
public bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
{
if (!enabled)
return true;
Sprite sprite = image.overrideSprite;
if (sprite == null)
return true;
Vector2 local;
RectTransformUtility.ScreenPointToLocalPointInRectangle(image.rectTransform, screenPoint, eventCamera, out local);
Rect rect = image.rectTransform.rect;
// Convert to have lower left corner as reference point.
local.x += image.rectTransform.pivot.x * rect.width;
local.y += image.rectTransform.pivot.y * rect.height;
float u = local.x / rect.width;
float v = local.y / rect.height;
try
{
if (!reversed)
return sprite.texture.GetPixelBilinear(u, v).a != 0;
else
return sprite.texture.GetPixelBilinear(u, v).a == 0;
}
catch (UnityException e)
{
Debug.LogException(e);
}
return true;
}
}
using UnityEngine;
using UnityEngine.UI;
[DisallowMultipleComponent]
[RequireComponent(typeof(RawImage))]
public class RawImageRaycastFilter : MonoBehaviour, ICanvasRaycastFilter
{
public bool reversed;
private RawImage rawImage;
void OnEnable()
{
rawImage = GetComponent<RawImage>();
}
public bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
{
if (!enabled)
return true;
Texture2D texture = rawImage.texture as Texture2D;
if (texture == null)
return true;
Vector2 local;
RectTransformUtility.ScreenPointToLocalPointInRectangle(rawImage.rectTransform, screenPoint, eventCamera, out local);
Rect rect = rawImage.rectTransform.rect;
// Convert to have lower left corner as reference point.
local.x += rawImage.rectTransform.pivot.x * rect.width;
local.y += rawImage.rectTransform.pivot.y * rect.height;
Rect uvRect = rawImage.uvRect;
float u = local.x / rect.width * uvRect.width + uvRect.x;
float v = local.y / rect.height * uvRect.height + uvRect.y;
try
{
if (!reversed)
return texture.GetPixelBilinear(u, v).a != 0;
else
return texture.GetPixelBilinear(u, v).a == 0;
}
catch (UnityException e)
{
Debug.LogException(e);
}
return true;
}
}
网友评论
float u = local.x / rect.width * uvRect.width + uvRect.x;
float v = local.y / rect.height * uvRect.height + uvRect.y;
这两句是什么意思呢?
local.x += image.rectTransform.pivot.x * rect.width;
local.y += image.rectTransform.pivot.y * rect.height;
这两句是将基于pivot获取的RectTransform本地坐标转换成相对于左下角(0,0)的坐标,对吗
float u = local.x / rect.width;
float v = local.y / rect.height;
这两句是将上面得到的坐标归一化为UV坐标,对吗