TargetDistanceLabel.cs 1.1 KB

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