WalkPos_Lerp.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. public class WalkPos_Lerp : MonoBehaviour
  5. {
  6. // Public Settings
  7. public float speed = 1.0f;
  8. // Waypoints and Rotations
  9. private Vector3 startPoint, endPoint;
  10. private Quaternion startRot, endRot;
  11. private List<Vector3> posList;
  12. private List<Quaternion> rotList;
  13. // Private Journey Settings
  14. private int currentStartPoint;
  15. private float startTime;
  16. private float journeyLength;
  17. //Animator
  18. private Animator anim;
  19. private void Start()
  20. {
  21. int index = gameObject.GetComponent<WriteInFile>().index;
  22. string dir = Directory.GetCurrentDirectory();
  23. string reference = @"\Assets\CSV_files\Walk" + index + ".txt";
  24. // var -> Tuple<List<Vector3>, List<Quaternion>>
  25. var posRotList = gameObject.GetComponent<ReadFromFile>().ReadFromTxtFile(dir + reference);
  26. posList = posRotList.Item1;
  27. rotList = posRotList.Item2;
  28. currentStartPoint = 0;
  29. transform.position = posList[0];
  30. transform.rotation = rotList[0];
  31. SetPoints();
  32. // Animation Walking
  33. anim = this.GetComponent<Animator>();
  34. anim.SetBool("isWalking", true);
  35. anim.SetBool("isIdle", false);
  36. }
  37. void SetPoints()
  38. {
  39. startPoint = posList[currentStartPoint];
  40. endPoint = posList[currentStartPoint + 1];
  41. startRot = rotList[currentStartPoint];
  42. endRot = rotList[currentStartPoint + 1];
  43. startTime = Time.time;
  44. journeyLength = Vector3.Distance(startPoint, endPoint);
  45. }
  46. // Update is called once per frame
  47. void Update()
  48. {
  49. float distCovered = (Time.time - startTime) * speed;
  50. float fracJourney = 1f;
  51. if (journeyLength != 0) fracJourney = distCovered / journeyLength;
  52. // Animation Idle, if startPoint == endPoint and startRot == endRot
  53. if (journeyLength == 0 && startRot == endRot)
  54. {
  55. anim.SetBool("isWalking", false);
  56. anim.SetBool("isIdle", true);
  57. }
  58. else if(!anim.GetBool("isWalking"))
  59. {
  60. anim.SetBool("isWalking", true);
  61. anim.SetBool("isIdle", false);
  62. }
  63. transform.position = Vector3.Lerp(startPoint, endPoint, fracJourney);
  64. transform.rotation = Quaternion.Lerp(startRot, endRot, fracJourney);
  65. if (fracJourney >= 1f && currentStartPoint + 2 < posList.Count && currentStartPoint + 2 < rotList.Count)
  66. {
  67. currentStartPoint++;
  68. SetPoints();
  69. }
  70. }
  71. }