TargetDistanceLabel.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class TargetDistanceLabel : MonoBehaviour
  6. {
  7. public RectTransform canvasRTF;
  8. public Camera mainCamera;
  9. public Transform followTarget;
  10. TargetBody targetBody;
  11. Vector3 centerPoint = new Vector3(0.5f, 0.5f, 0);
  12. Text textComp;
  13. void Start()
  14. {
  15. targetBody = GameObject.Find("GameArea/010").GetComponentInChildren<TargetBody>();
  16. textComp = this.GetComponent<Text>();
  17. }
  18. void LateUpdate()
  19. {
  20. float angle = Vector3.Angle(mainCamera.transform.forward, followTarget.position - mainCamera.transform.position);
  21. if (angle > 90) {
  22. textComp.enabled = false;
  23. return;
  24. } else {
  25. textComp.enabled = true;
  26. }
  27. Vector3 v3 = mainCamera.WorldToViewportPoint(followTarget.position) - centerPoint;
  28. v3.x *= canvasRTF.rect.width;
  29. v3.y *= canvasRTF.rect.height;
  30. v3.z = 0;
  31. this.transform.localPosition = v3;
  32. textComp.text = ((int)Mathf.Round(targetBody.GetDistance())) + "M";
  33. }
  34. }