summaryrefslogtreecommitdiff
path: root/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/ExampleScenes/Scenes/HexagonalTurnBased/TurnBasedDoor.cs
blob: efe96fb17ceb29eb1cea009e9b67267b9688bb88 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace Pathfinding.Examples {
	/// <summary>Helper script in the example scene 'Turn Based'</summary>
	[RequireComponent(typeof(Animator))]
	[RequireComponent(typeof(SingleNodeBlocker))]
	[HelpURL("https://arongranberg.com/astar/documentation/stable/turnbaseddoor.html")]
	public class TurnBasedDoor : MonoBehaviour {
		Animator animator;
		SingleNodeBlocker blocker;

		bool open;

		void Awake () {
			animator = GetComponent<Animator>();
			blocker = GetComponent<SingleNodeBlocker>();
		}

		void Start () {
			// Make sure the door starts out blocked
			blocker.BlockAtCurrentPosition();
			animator.CrossFade("close", 0.2f);
		}

		public void Close () {
			StartCoroutine(WaitAndClose());
		}

		IEnumerator WaitAndClose () {
			var selector = new List<SingleNodeBlocker>() { blocker };
			var node = AstarPath.active.GetNearest(transform.position).node;

			// Wait while there is another SingleNodeBlocker occupying the same node as the door
			// this is likely another unit which is standing on the door node, and then we cannot
			// close the door
			if (blocker.manager.NodeContainsAnyExcept(node, selector)) {
				// Door is blocked
				animator.CrossFade("blocked", 0.2f);
			}

			while (blocker.manager.NodeContainsAnyExcept(node, selector)) {
				yield return null;
			}

			open = false;
			animator.CrossFade("close", 0.2f);
			blocker.BlockAtCurrentPosition();
		}

		public void Open () {
			// Stop WaitAndClose if it is running
			StopAllCoroutines();

			// Play the open door animation
			animator.CrossFade("open", 0.2f);
			open = true;

			// Unblock the door node so that units can traverse it again
			blocker.Unblock();
		}

		public void Toggle () {
			if (open) {
				Close();
			} else {
				Open();
			}
		}
	}
}