1 using UnityEngine;
2 using
UnityEngine.UI;
3 using
System.Collections;
4
5 public
class AlphaButtonClickMask : MonoBehaviour, ICanvasRaycastFilter
6 {
7     
protected Image _image;
8
9     
public void Start()
10     {
11         _image = GetComponent<Image>();
12
13         Texture2D tex = _image.sprite.texture
as Texture2D;
14
15         
bool isInvalid = false;
16         
if (tex != null)
17         {
18             
try
19             {
20                 tex.GetPixels32();
21             }
22             
catch (UnityException e)
23             {
24                 Debug.LogError(e.Message);
25                 isInvalid =
true;
26             }
27         }
28         
else
29         {
30             isInvalid =
true;
31         }
32
33         
if (isInvalid)
34         {
35             Debug.LogError(
"This script need an Image with a readbale Texture2D to work.");
36         }
37     }
38
39     
public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
40     {
41         Vector2 localPoint;
42         RectTransformUtility.ScreenPointToLocalPointInRectangle(_image.rectTransform, sp, eventCamera,
out localPoint);
43
44         Vector2 normalizedLocal =
new Vector2(1.0f + localPoint.x / _image.rectTransform.rect.width, 1.0f + localPoint.y / _image.rectTransform.rect.height);
45         Vector2 uv =
new Vector2(
46             _image.sprite.rect.x + normalizedLocal.x * _image.sprite.rect.width,
47             _image.sprite.rect.y + normalizedLocal.y * _image.sprite.rect.height );
48
49         uv.x /= _image.sprite.texture.width;
50         uv.y /= _image.sprite.texture.height;
51
52         
//uv are inversed, as 0,0 or the rect transform seem to be upper right, then going negativ toward lower left...
53         Color c = _image.sprite.texture.GetPixelBilinear(uv.x, uv.y);
54
55         
return c.a> 0.1f;
56     }
57 }


uv are inversed, as 0,0 or the rect transform seem to be upper right, then going negativ toward lower left...



Gõ tìm kiếm nhanh...