TargetDistanceLabel.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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 Transform followTarget;
  10. TargetBody targetBody;
  11. Vector3 centerPoint = new Vector3(0.5f, 0.5f, 0);
  12. Text textComp;
  13. Canvas parentCanvas;
  14. void Start()
  15. {
  16. targetBody = GameObject.Find("GameArea/TargetObject").GetComponentInChildren<TargetBody>();
  17. textComp = this.GetComponent<Text>();
  18. parentCanvas = transform.parent.GetComponent<Canvas>();
  19. }
  20. void LateUpdate()
  21. {
  22. Camera mainCamera = BowCamera.ins.GetRenderCamera();
  23. parentCanvas.worldCamera = mainCamera;
  24. float angle = Vector3.Angle(mainCamera.transform.forward, followTarget.position - mainCamera.transform.position);
  25. if (angle > 90) {
  26. textComp.enabled = false;
  27. return;
  28. } else {
  29. textComp.enabled = true;
  30. }
  31. Vector3 v3 = mainCamera.WorldToViewportPoint(followTarget.position) - centerPoint;
  32. v3.x *= canvasRTF.rect.width;
  33. v3.y *= canvasRTF.rect.height;
  34. v3.z = 0;
  35. this.transform.localPosition = v3;
  36. textComp.text = ((int)Mathf.Round(targetBody.GetDistance())) + "M";
  37. }
  38. }