AlphaButtonClickMask.cs 1.7 KB

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