PathFollow.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class PathFollow : BaseBehaviour
  5. {
  6. public BoxCollider2D _boxCollider { get; private set; }
  7. public void Start()
  8. {
  9. if (this.Path == null)
  10. {
  11. UnityEngine.Debug.LogError("Path Cannot be null", base.gameObject);
  12. return;
  13. }
  14. if (base.transform.GetComponent<BoxCollider2D>() != null)
  15. {
  16. this._boxCollider = base.transform.GetComponent<BoxCollider2D>();
  17. }
  18. this._currentPoint = this.Path.GetPathEnumerator();
  19. this._currentPoint.MoveNext();
  20. if (this._currentPoint.Current == null)
  21. {
  22. return;
  23. }
  24. base.transform.position = this._currentPoint.Current.position;
  25. }
  26. public void FixedUpdate()
  27. {
  28. if (this._currentPoint == null || this._currentPoint.Current == null)
  29. {
  30. return;
  31. }
  32. Vector3 position = base.transform.position;
  33. if (this.Type == PathFollow.FollowType.MoveTowards)
  34. {
  35. base.transform.position = Vector3.MoveTowards(base.transform.position, this._currentPoint.Current.position, Time.fixedDeltaTime * this.Speed);
  36. }
  37. else if (this.Type == PathFollow.FollowType.Lerp)
  38. {
  39. base.transform.position = Vector3.Lerp(base.transform.position, this._currentPoint.Current.position, Time.fixedDeltaTime * this.Speed);
  40. }
  41. float sqrMagnitude = (base.transform.position - this._currentPoint.Current.position).sqrMagnitude;
  42. if (sqrMagnitude < this.MaxDistanceToGoal * this.MaxDistanceToGoal)
  43. {
  44. this._currentPoint.MoveNext();
  45. }
  46. Vector3 position2 = base.transform.position;
  47. this.CurrentSpeed = (position2 - position) / Time.fixedDeltaTime;
  48. }
  49. public PathFollow.FollowType Type;
  50. public PathDefinition Path;
  51. public float Speed = 1f;
  52. public float MaxDistanceToGoal = 0.1f;
  53. public Vector3 CurrentSpeed;
  54. private IEnumerator<Transform> _currentPoint;
  55. public enum FollowType
  56. {
  57. MoveTowards,
  58. Lerp
  59. }
  60. }