MissText.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Collections;
  3. using TMPro;
  4. using UnityEngine;
  5. using UnityEngine.PlayerLoop;
  6. namespace Comp
  7. {
  8. public class MissText : MonoBehaviour
  9. {
  10. private Transform _targetObject; // 目标物体
  11. private const float Speed = 0.3f; // 移动速度
  12. private const float High = 0.7f;
  13. // 淡出相关
  14. private TextMeshPro _textMeshPro;
  15. private const float FadeTime = 1f;
  16. private float _timePassed = 0f;
  17. public void SetTarget(Transform transform)
  18. {
  19. _targetObject = transform;
  20. var position = transform.position;
  21. this.transform.position = new Vector3(position.x, High, position.z);
  22. }
  23. private void Start()
  24. {
  25. _textMeshPro = GetComponent<TextMeshPro>();
  26. }
  27. public void FixedUpdate()
  28. {
  29. if (_targetObject != null)
  30. {
  31. var position = _targetObject.position;
  32. var position1 = transform.position;
  33. transform.Translate(new Vector3(position.x - position1.x,
  34. Vector3.up.y * (Speed * Time.deltaTime), position.z - position1.z));
  35. }
  36. // 计算当前已经过去的时间
  37. _timePassed += Time.deltaTime;
  38. // 计算当前的透明度
  39. float alpha = Mathf.Lerp(1f, 0f, _timePassed / FadeTime);
  40. _textMeshPro.alpha = alpha;
  41. // 如果透明度已经为0,就销毁游戏对象
  42. if (alpha <= 0f)
  43. {
  44. Destroy(gameObject);
  45. }
  46. }
  47. }
  48. }