UIOverlay.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using UnityEngine;
  2. namespace Rokid.UXR.Utility
  3. {
  4. [ExecuteAlways]
  5. public class UIOverlay : MonoBehaviour
  6. {
  7. /// <summary>
  8. /// panel distance
  9. /// </summary>
  10. [SerializeField]
  11. private float panelDistance = 10;
  12. /// <summary>
  13. /// screen width
  14. /// </summary>
  15. private float width = 1920;
  16. /// <summary>
  17. /// screen heigh
  18. /// </summary>
  19. private float height = 1200;
  20. private Canvas canvas;
  21. private FollowCamera followCamera;
  22. private RectTransform rectTransform;
  23. private float prePanelDistance;
  24. private void Start()
  25. {
  26. SetFollowCamera();
  27. SetCanvasParam();
  28. SetRectParam();
  29. }
  30. private void SetFollowCamera()
  31. {
  32. followCamera = GetComponent<FollowCamera>();
  33. if (followCamera == null)
  34. {
  35. followCamera = gameObject.AddComponent<FollowCamera>();
  36. }
  37. followCamera.offsetPosition = new Vector3(0, 0, panelDistance);
  38. }
  39. private void SetCanvasParam()
  40. {
  41. canvas = GetComponent<Canvas>();
  42. if (canvas == null)
  43. {
  44. canvas = GetComponentInChildren<Canvas>();
  45. }
  46. if (canvas == null)
  47. {
  48. canvas = gameObject.AddComponent<Canvas>();
  49. }
  50. canvas.renderMode = RenderMode.WorldSpace;
  51. }
  52. private void SetRectParam()
  53. {
  54. width = Utils.IsAndroidPlatfrom() ? Screen.width / 2 : Screen.width;
  55. height = Screen.height;
  56. rectTransform = canvas.GetComponent<RectTransform>();
  57. if (rectTransform == null)
  58. {
  59. rectTransform = gameObject.AddComponent<RectTransform>();
  60. }
  61. rectTransform.sizeDelta = new Vector2(width, height);
  62. Vector3[] corners = Utils.GetCameraCorners(panelDistance);
  63. float uiWidth = corners[1].x - corners[0].x;
  64. float uiHeight = corners[0].y - corners[3].y;
  65. rectTransform.localScale = new Vector3(uiWidth / width, uiHeight / height, 1);
  66. rectTransform.localPosition = Vector3.zero;
  67. #region Pivot Adjust
  68. // Vector4 halffovtan = Utils.HalfFovTan;
  69. // rectTransform.pivot = new Vector2(halffovtan.x / (halffovtan.x + halffovtan.y), (halffovtan.w) / (halffovtan.z + halffovtan.w));
  70. // Vector3[] corners = new Vector3[4];
  71. // rectTransform.GetWorldCorners(corners);
  72. // RKLog.KeyInfo($"====UIOverLay==== pivot: {rectTransform.pivot} anchorPositoin:{rectTransform.anchoredPosition3D},worldcorners:{corners[0]},{corners[1]},{corners[2]},{corners[3]}");
  73. #endregion
  74. prePanelDistance = panelDistance;
  75. }
  76. private void Update()
  77. {
  78. if (prePanelDistance != panelDistance)
  79. {
  80. SetFollowCamera();
  81. SetRectParam();
  82. }
  83. }
  84. }
  85. }