当前位置:   article > 正文

unity中TMP_Text文字显示波浪和上下移动

unity中TMP_Text文字显示波浪和上下移动

sin函数来表示

  1. using UnityEngine;
  2. using TMPro;
  3. using System.Collections;
  4. public class WaveTextAnimation : MonoBehaviour
  5. {
  6. public float amplitude = 0.3f;
  7. public float frequency = 2f;
  8. private TMP_Text textComponent;
  9. private string originalText;
  10. private void Start()
  11. {
  12. textComponent = GetComponent<TMP_Text>();
  13. originalText = textComponent.text;
  14. }
  15. private void Update()
  16. {
  17. // 根据时间计算波浪形的偏移量
  18. float offset = Mathf.Sin(Time.time * frequency) * amplitude;
  19. // 应用波浪形偏移量到每个字符
  20. for (int i = 0; i < originalText.Length; i++)
  21. {
  22. TMP_CharacterInfo charInfo = textComponent.textInfo.characterInfo[i];
  23. // 跳过空格和换行符
  24. if (!char.IsWhiteSpace(originalText[i]))
  25. {
  26. int materialIndex = charInfo.materialReferenceIndex;
  27. int vertexIndex = charInfo.vertexIndex;
  28. // 计算每个字符的顶点偏移
  29. Vector3[] vertices = textComponent.textInfo.meshInfo[materialIndex].vertices;
  30. for (int j = 0; j < 4; j++)
  31. {
  32. // vertices[vertexIndex + j] += new Vector3(0f, offset, 0f);
  33. var orig = vertices[vertexIndex + j];
  34. vertices[vertexIndex + j]=orig+new Vector3(0, Mathf.Sin(Time.time*frequency+orig.x*frequency)*amplitude, 0);
  35. }
  36. }
  37. }
  38. // 更新文本网格的顶点信息
  39. for (int i = 0; i < textComponent.textInfo.meshInfo.Length; i++)
  40. {
  41. textComponent.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
  42. }
  43. }
  44. }

文本上下移动

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class TextWaveMotion : MonoBehaviour
  5. {
  6. public float amplitude = 1f;
  7. public float frequency = 1f;
  8. private float startTime;
  9. private void Start()
  10. {
  11. startTime = Time.time;
  12. }
  13. private void Update()
  14. {
  15. // 计算波浪形变化
  16. float waveValue = Mathf.Sin((Time.time - startTime) * frequency) * amplitude;
  17. // 应用波浪形变化到文本对象的位置
  18. transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y+waveValue, transform.localPosition.z);
  19. }
  20. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/86479
推荐阅读
相关标签
  

闽ICP备14008679号