当前位置:   article > 正文

unity中简单的时间回溯功能_unity 怎么更好的做事件流 及事件回溯

unity 怎么更好的做事件流 及事件回溯

先创建要回溯的信息类

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class TimeRecord
  5. {
  6. public Vector3 postion;
  7. public Quaternion rotation;
  8. public TimeRecord(Vector3 postion, Quaternion rotation)
  9. {
  10. this.postion = postion;
  11. this.rotation = rotation;
  12. }
  13. }

回溯时间

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class TimeRollback : MonoBehaviour
  5. {
  6. public float speed;
  7. public float RecordTime;
  8. bool isRollBack;
  9. List<TimeRecord> timeRecordList;
  10. private void Start()
  11. {
  12. timeRecordList = new List<TimeRecord>();
  13. }
  14. private void Update()
  15. {
  16. if (Input.GetKeyDown(KeyCode.Space))
  17. {
  18. isRollBack=true;
  19. }
  20. }
  21. private void FixedUpdate()
  22. {
  23. if (isRollBack)
  24. {
  25. RollBackTimeInformation();
  26. }
  27. else
  28. {
  29. RecordTimeInformation();
  30. transform.position += Vector3.right * speed * Time.fixedDeltaTime;
  31. }
  32. }
  33. //记录信息
  34. public void RecordTimeInformation()
  35. {
  36. //Mathf.Round用于对浮点数进行四舍五入。
  37. if (timeRecordList.Count >Mathf.Round( RecordTime/Time.deltaTime))
  38. {
  39. //移除最后一个元素
  40. timeRecordList.RemoveAt(timeRecordList.Count-1);
  41. }
  42. timeRecordList.Insert(0, new TimeRecord(transform.position, transform.rotation));
  43. }
  44. //回溯时间
  45. public void RollBackTimeInformation()
  46. {
  47. if(timeRecordList.Count>0)
  48. {
  49. transform.position = timeRecordList[0].postion;
  50. transform.rotation = timeRecordList[0].rotation;
  51. //移除下标为零的元素
  52. timeRecordList.RemoveAt(0);
  53. }
  54. else
  55. {
  56. isRollBack = false;
  57. }
  58. }
  59. }

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

闽ICP备14008679号