ObsIconCtrl.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.EventSystems;
  6. using UnityEngine.UI;
  7. using UnityEngine.UIElements;
  8. public class ObsIconCtrl : MonoBehaviour,IPointerEnterHandler,IPointerExitHandler
  9. {
  10. private RectTransform rect;
  11. private Camera _camera;
  12. private UnityEngine.UI.Button _button;
  13. public ObsData _data;
  14. public Transform targetTransForm;
  15. public GameObject tint;
  16. public Text tintName;
  17. public void Init(ObsData data)
  18. {
  19. _data = data;
  20. tintName.text = data.name;
  21. rect = this.GetComponent<RectTransform>();
  22. _button = this.transform.Find("Icon").GetComponent<UnityEngine.UI.Button>();
  23. if (!data.status)
  24. {
  25. this.transform.Find("Icon").GetComponent<UnityEngine.UI.Image>().color = Color.red;
  26. this.transform.Find("Icon").GetChild(0).GetComponent<UnityEngine.UI.Image>().color = Color.red;
  27. }
  28. else
  29. {
  30. _button.onClick.AddListener(() =>
  31. {
  32. GCJKLayer._Instance.ShowObsPlayerPanel(_data);
  33. });
  34. }
  35. rect.anchoredPosition = new Vector2(2000, 0);
  36. _camera = CameraManager.instance.mainCamera;
  37. targetTransForm=StaticLod.instance.GetStaticObj(_data.targetName).transform;
  38. }
  39. void Update()
  40. {
  41. if (targetTransForm != null)
  42. {
  43. if (IsObjectInCameraView(targetTransForm, _camera))
  44. {
  45. rect.transform.position=_camera.WorldToScreenPoint(targetTransForm.position);
  46. }
  47. else
  48. {
  49. rect.transform.position = new Vector3(2000, 0, 0);
  50. }
  51. }
  52. }
  53. bool IsObjectInCameraView(Transform objectTransform, Camera camera)
  54. {
  55. Vector3 objectScreenPosition = camera.WorldToScreenPoint(objectTransform.position);
  56. return objectScreenPosition.z > 0 &&
  57. objectScreenPosition.x > 0 &&
  58. objectScreenPosition.x < Screen.width &&
  59. objectScreenPosition.y > 0 &&
  60. objectScreenPosition.y < Screen.height;
  61. }
  62. public void OnPointerEnter(PointerEventData eventData)
  63. {
  64. tint.gameObject.SetActive(true);
  65. LayoutRebuilder.ForceRebuildLayoutImmediate(tintName.GetComponent<RectTransform>()); // 强制重新计算布局
  66. LayoutRebuilder.ForceRebuildLayoutImmediate(tint.GetComponent<RectTransform>()); // 强制重新计算布局
  67. }
  68. public void OnPointerExit(PointerEventData eventData)
  69. {
  70. tint.gameObject.SetActive(false);
  71. }
  72. }