using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[RequireComponent
(typeof(UIWidget
))] public class UIHitAlphaTest : MonoBehaviour
{
[Range(0.01f,1f)]
public float threshold = 0.5f;
List
<UIWidget
> childs
= new List
<UIWidget
>();
void Start ()
{
UIWidget w = GetComponent<UIWidget>();
w.hitCheck = HitCheck;
childs.Add(w);
childs.AddRange(w.GetComponentsInChildren<UIWidget>());
}
Vector3 t1p1 = Vector3.zero;
Vector3 t1p2 = Vector3.zero;
Vector3 t1p3 = Vector3.zero;
Vector3 t2p1 = Vector3.zero;
Vector3 t2p2 = Vector3.zero;
Vector3 t2p3 = Vector3.zero;
Vector2 t1uv1 = Vector2.zero;
Vector2 t1uv2 = Vector2.zero;
Vector2 t1uv3 = Vector2.zero;
Vector2 t2uv1 = Vector2.zero;
Vector2 t2uv2 = Vector2.zero;
Vector2 t2uv3 = Vector2.zero;
bool HitCheck(Vector3 worldPos)
{
for (int widgetIndex = 0; widgetIndex < childs.Count; widgetIndex++)
{
UIWidget widget = childs[widgetIndex];
Vector3 localPos = widget.cachedTransform.InverseTransformPoint(worldPos);
Texture2D tex = widget.mainTexture as Texture2D;
for( int i = 0; i < widget.geometry.verts.size; i += 4 )
{
t1p1 = widget.geometry.verts.buffer[i];
t1p2 = widget.geometry.verts.buffer[i + 1];
t1p3 = widget.geometry.verts.buffer[i + 2];
t2p1 = widget.geometry.verts.buffer[i + 2];
t2p2 = widget.geometry.verts.buffer[i + 3];
t2p3 = widget.geometry.verts.buffer[i];
t1uv1 = widget.geometry.uvs.buffer[i];
t1uv2 = widget.geometry.uvs.buffer[i + 1];
t1uv3 = widget.geometry.uvs.buffer[i + 2];
t2uv1 = widget.geometry.uvs.buffer[i + 2];
t2uv2 = widget.geometry.uvs.buffer[i + 3];
t2uv3 = widget.geometry.uvs.buffer[i];
bool t1 = CheckTriangle
(localPos,
t1p1, t1p2, t1p3,
t1uv1, t1uv2, t1uv3,
tex);
bool t2 = CheckTriangle
(localPos,
t2p1, t2p2, t2p3,
t2uv1, t2uv2, t2uv3,
tex);
if (t1 || t2)
{
return true;
}
}
}
return false;
}
bool CheckTriangle(Vector3 pos, Vector3 v1, Vector3 v2, Vector3 v3, Vector2 uv1, Vector2 uv2, Vector2 uv3, Texture2D tex)
{
// Normal of triangle
Vector3 normal = Vector3.Cross( v3-v1, v2-v1 );
if( normal.sqrMagnitude < 0.01f )
return false;
pos = pos - Vector3.Dot( pos-v1, normal ) * normal; // Project point onto plane
float xScale = (pos.x - v2.x) / (v3.x - v2.x);
float yScale = (pos.y - v1.y) / (v2.y - v1.y);
Vector2 finalUV
= new Vector2
(uv2
.x + (uv3
.x - uv2
.x) * xScale, uv1
.y + (uv2
.y - uv1
.y) * yScale
); Color pixel = tex.GetPixel( (int)(finalUV.x * tex.width), (int)(finalUV.y * tex.height) );
return pixel.a >= threshold;
}
}