Support.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using UnityEngine;
  2. namespace WebGLSupport.Detail
  3. {
  4. public static class Support
  5. {
  6. /// <summary>
  7. /// 画面内の描画範囲を取得する
  8. /// </summary>
  9. /// <param name="uiElement"></param>
  10. /// <returns></returns>
  11. public static Rect GetScreenCoordinates(RectTransform uiElement)
  12. {
  13. var worldCorners = new Vector3[4];
  14. uiElement.GetWorldCorners(worldCorners);
  15. // try to support RenderMode:WorldSpace
  16. var canvas = uiElement.GetComponentInParent<Canvas>();
  17. var useCamera = (canvas.renderMode != RenderMode.ScreenSpaceOverlay);
  18. if (canvas && useCamera)
  19. {
  20. var camera = canvas.worldCamera;
  21. if (!camera) camera = Camera.main;
  22. for (var i = 0; i < worldCorners.Length; i++)
  23. {
  24. worldCorners[i] = camera.WorldToScreenPoint(worldCorners[i]);
  25. }
  26. }
  27. var min = new Vector3(float.MaxValue, float.MaxValue);
  28. var max = new Vector3(float.MinValue, float.MinValue);
  29. for (var i = 0; i < worldCorners.Length; i++)
  30. {
  31. min.x = Mathf.Min(min.x, worldCorners[i].x);
  32. min.y = Mathf.Min(min.y, worldCorners[i].y);
  33. max.x = Mathf.Max(max.x, worldCorners[i].x);
  34. max.y = Mathf.Max(max.y, worldCorners[i].y);
  35. }
  36. return new Rect(min.x, min.y, max.x - min.x, max.y - min.y);
  37. }
  38. }
  39. }