SingleNodeBlocker.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using UnityEngine;
  2. namespace Pathfinding {
  3. /// <summary>
  4. /// Blocks single nodes in a graph.
  5. ///
  6. /// This is useful in turn based games where you want
  7. /// units to avoid all other units while pathfinding
  8. /// but not be blocked by itself.
  9. ///
  10. /// Note: This cannot be used together with any movement script
  11. /// as the nodes are not blocked in the normal way.
  12. /// See: TurnBasedAI for example usage
  13. ///
  14. /// See: BlockManager
  15. /// See: turnbased (view in online documentation for working links)
  16. /// </summary>
  17. [HelpURL("http://arongranberg.com/astar/documentation/stable/class_pathfinding_1_1_single_node_blocker.php")]
  18. public class SingleNodeBlocker : VersionedMonoBehaviour {
  19. public GraphNode lastBlocked { get; private set; }
  20. public BlockManager manager;
  21. /// <summary>
  22. /// Block node closest to the position of this object.
  23. ///
  24. /// Will unblock the last node that was reserved (if any)
  25. /// </summary>
  26. public void BlockAtCurrentPosition () {
  27. BlockAt(transform.position);
  28. }
  29. /// <summary>
  30. /// Block node closest to the specified position.
  31. ///
  32. /// Will unblock the last node that was reserved (if any)
  33. /// </summary>
  34. public void BlockAt (Vector3 position) {
  35. Unblock();
  36. var node = AstarPath.active.GetNearest(position, NNConstraint.None).node;
  37. if (node != null) {
  38. Block(node);
  39. }
  40. }
  41. /// <summary>
  42. /// Block specified node.
  43. ///
  44. /// Will unblock the last node that was reserved (if any)
  45. /// </summary>
  46. public void Block (GraphNode node) {
  47. if (node == null)
  48. throw new System.ArgumentNullException("node");
  49. manager.InternalBlock(node, this);
  50. lastBlocked = node;
  51. }
  52. /// <summary>Unblock the last node that was blocked (if any)</summary>
  53. public void Unblock () {
  54. if (lastBlocked == null || lastBlocked.Destroyed) {
  55. lastBlocked = null;
  56. return;
  57. }
  58. manager.InternalUnblock(lastBlocked, this);
  59. lastBlocked = null;
  60. }
  61. }
  62. }