AnimationLinkTraverser.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System.Collections;
  2. using UnityEngine;
  3. namespace Pathfinding.Examples {
  4. using Pathfinding;
  5. /// <summary>
  6. /// Example of how to handle off-mesh link traversal.
  7. /// This is used in the "Example4_Recast_Navmesh2" example scene.
  8. ///
  9. /// See: <see cref="Pathfinding.RichAI"/>
  10. /// See: <see cref="Pathfinding.RichAI.onTraverseOffMeshLink"/>
  11. /// See: <see cref="Pathfinding.AnimationLink"/>
  12. /// </summary>
  13. [HelpURL("http://arongranberg.com/astar/documentation/stable/class_pathfinding_1_1_examples_1_1_animation_link_traverser.php")]
  14. public class AnimationLinkTraverser : VersionedMonoBehaviour {
  15. public Animation anim;
  16. RichAI ai;
  17. void OnEnable () {
  18. ai = GetComponent<RichAI>();
  19. if (ai != null) ai.onTraverseOffMeshLink += TraverseOffMeshLink;
  20. }
  21. void OnDisable () {
  22. if (ai != null) ai.onTraverseOffMeshLink -= TraverseOffMeshLink;
  23. }
  24. protected virtual IEnumerator TraverseOffMeshLink (RichSpecial rs) {
  25. var link = rs.nodeLink as AnimationLink;
  26. if (link == null) {
  27. Debug.LogError("Unhandled RichSpecial");
  28. yield break;
  29. }
  30. // Rotate character to face the correct direction
  31. while (true) {
  32. var origRotation = ai.rotation;
  33. var finalRotation = ai.SimulateRotationTowards(rs.first.forward, ai.rotationSpeed * Time.deltaTime);
  34. // Rotate until the rotation does not change anymore
  35. if (origRotation == finalRotation) break;
  36. ai.FinalizeMovement(ai.position, finalRotation);
  37. yield return null;
  38. }
  39. // Reposition
  40. transform.parent.position = transform.position;
  41. transform.parent.rotation = transform.rotation;
  42. transform.localPosition = Vector3.zero;
  43. transform.localRotation = Quaternion.identity;
  44. // Set up animation speeds
  45. if (rs.reverse && link.reverseAnim) {
  46. anim[link.clip].speed = -link.animSpeed;
  47. anim[link.clip].normalizedTime = 1;
  48. anim.Play(link.clip);
  49. anim.Sample();
  50. } else {
  51. anim[link.clip].speed = link.animSpeed;
  52. anim.Rewind(link.clip);
  53. anim.Play(link.clip);
  54. }
  55. // Fix required for animations in reverse direction
  56. transform.parent.position -= transform.position-transform.parent.position;
  57. // Wait for the animation to finish
  58. yield return new WaitForSeconds(Mathf.Abs(anim[link.clip].length/link.animSpeed));
  59. }
  60. }
  61. }