TurnBasedDoor.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. namespace Pathfinding.Examples {
  5. /// <summary>Helper script in the example scene 'Turn Based'</summary>
  6. [RequireComponent(typeof(Animator))]
  7. [RequireComponent(typeof(SingleNodeBlocker))]
  8. [HelpURL("http://arongranberg.com/astar/documentation/stable/class_pathfinding_1_1_examples_1_1_turn_based_door.php")]
  9. public class TurnBasedDoor : MonoBehaviour {
  10. Animator animator;
  11. SingleNodeBlocker blocker;
  12. bool open;
  13. void Awake () {
  14. animator = GetComponent<Animator>();
  15. blocker = GetComponent<SingleNodeBlocker>();
  16. }
  17. void Start () {
  18. // Make sure the door starts out blocked
  19. blocker.BlockAtCurrentPosition();
  20. animator.CrossFade("close", 0.2f);
  21. }
  22. public void Close () {
  23. StartCoroutine(WaitAndClose());
  24. }
  25. IEnumerator WaitAndClose () {
  26. var selector = new List<SingleNodeBlocker>() { blocker };
  27. var node = AstarPath.active.GetNearest(transform.position).node;
  28. // Wait while there is another SingleNodeBlocker occupying the same node as the door
  29. // this is likely another unit which is standing on the door node, and then we cannot
  30. // close the door
  31. if (blocker.manager.NodeContainsAnyExcept(node, selector)) {
  32. // Door is blocked
  33. animator.CrossFade("blocked", 0.2f);
  34. }
  35. while (blocker.manager.NodeContainsAnyExcept(node, selector)) {
  36. yield return null;
  37. }
  38. open = false;
  39. animator.CrossFade("close", 0.2f);
  40. blocker.BlockAtCurrentPosition();
  41. }
  42. public void Open () {
  43. // Stop WaitAndClose if it is running
  44. StopAllCoroutines();
  45. // Play the open door animation
  46. animator.CrossFade("open", 0.2f);
  47. open = true;
  48. // Unblock the door node so that units can traverse it again
  49. blocker.Unblock();
  50. }
  51. public void Toggle () {
  52. if (open) {
  53. Close();
  54. } else {
  55. Open();
  56. }
  57. }
  58. }
  59. }