summaryrefslogtreecommitdiff
path: root/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/ExampleScenes/Scenes/OldExamples/Example18_RTS/RTSUnit.cs
blob: b1e0b9c9821d3787560922b9fb39ca9220e20531 (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.Profiling;

namespace Pathfinding.Examples.RTS {
	using Pathfinding;
	using Pathfinding.RVO;
	using Pathfinding.Util;

	[HelpURL("https://arongranberg.com/astar/documentation/stable/rtsunit.html")]
	public class RTSUnit : VersionedMonoBehaviour {
		public GameObject selectionIndicator;
		public GameObject deathEffect;
		public int team;
		public float detectionRange;

		public float maxHealth;

		public enum Type {
			Infantry,
			Heavy,
			Worker,
			Harvester,

			HarvesterDropoff = 100,
			HarvesterDropoffQueue,
			ResourceCrystal = 200,
		}

		public Type type;
		[System.NonSerialized]
		public float health;
		IAstarAI ai;
		RVOController rvo;
		MovementMode movementMode;
		Vector3 lastDestination;
		RTSUnit attackTarget;
		RTSWeapon weapon;
		float lastSeenAttackTarget = float.NegativeInfinity;
		bool reachedDestination;
		public int storedCrystals;
		public RTSUnit reservedBy;
		public bool locked;
		new Transform transform;

		/// <summary>Position at the start of the current frame</summary>
		protected Vector3 position;

		public System.Action<bool> onMakeActiveUnit;

		public RTSPlayer owner {
			get {
				return RTSManager.instance.GetPlayer(team);
			}
		}

		public bool selectionIndicatorEnabled {
			get {
				if (selectionIndicator == null) return false;
				return selectionIndicator.activeSelf;
			}
			set {
				if (selectionIndicator != null) selectionIndicator.SetActive(value);
			}
		}

		public RTSHarvestableResource resource {
			get {
				return GetComponent<RTSHarvestableResource>();
			}
		}

		public float radius {
			get {
				return rvo != null ? rvo.radius : 1f;
			}
		}

		bool mSelected;
		public bool selected {
			get {
				return mSelected;
			}
			set {
				mSelected = value;
				selectionIndicatorEnabled = value;
				if (value) {
					RTSManager.instance.units.OnSelected(this);
				} else {
					RTSManager.instance.units.OnDeselected(this);
				}
			}
		}

		public void OnMakeActiveUnit (bool active) {
			if (onMakeActiveUnit != null) onMakeActiveUnit(active);
		}

		public void SetDestination (Vector3 destination, MovementMode mode) {
			if (ai != null && this) {
				reachedDestination = false;
				movementMode = mode;
				ai.destination = lastDestination = destination;
				(ai as AIBase).rvoDensityBehavior.ClearDestinationReached();
				ai.SearchPath();
				if (mode == MovementMode.Move) {
					attackTarget = null;
				}
			}
		}

		protected override void Awake () {
			base.Awake();
			transform = (this as MonoBehaviour).transform;
			ai = GetComponent<IAstarAI>();
			rvo = GetComponent<RVOController>();
			weapon = GetComponent<RTSWeapon>();
		}

		static System.Action<RTSUnit[], int> OnUpdateDelegate;
		void OnEnable () {
			if (OnUpdateDelegate == null) OnUpdateDelegate = OnUpdate;
			RTSManager.instance.units.AddUnit(this);
			selected = false;
			health = maxHealth;
			movementMode = MovementMode.AttackMove;
			reachedDestination = true;
			if (ai != null) lastDestination = ai.destination;
			BatchedEvents.Add(this, BatchedEvents.Event.Update, OnUpdateDelegate);
		}

		void OnDisable () {
			BatchedEvents.Remove(this);
			if (RTSManager.instance != null) RTSManager.instance.units.RemoveUnit(this);
		}

		static void OnUpdate (RTSUnit[] units, int count) {
			// Get some lists and arrays from an object pool
			List<RTSUnit>[] unitsByOwner = ArrayPool<List<RTSUnit> >.ClaimWithExactLength(RTSManager.instance.PlayerCount);
			for (int i = 0; i < unitsByOwner.Length; i++) {
				unitsByOwner[i] = ListPool<RTSUnit>.Claim();
			}
			for (int i = 0; i < count; i++) {
				units[i].position = units[i].transform.position;
				unitsByOwner[units[i].owner.index].Add(units[i]);
			}
			for (int i = 0; i < count; i++) {
				units[i].OnUpdate(unitsByOwner);
			}

			// Release allocated lists back to a pool
			for (int i = 0; i < unitsByOwner.Length; i++) {
				ListPool<RTSUnit>.Release(ref unitsByOwner[i]);
			}
			ArrayPool<List<RTSUnit> >.Release(ref unitsByOwner, true);
		}

		// Update is called once per frame
		protected virtual void OnUpdate (List<RTSUnit>[] unitsByOwner) {
			if (ai == null) {
				// Stationary unit

				if (weapon != null) {
					float minDist = detectionRange*detectionRange;
					for (int player = 0; player < unitsByOwner.Length; player++) {
						if (!owner.IsHostile(RTSManager.instance.GetPlayer(player))) continue;

						for (int i = 0; i < unitsByOwner[player].Count; i++) {
							var unit = unitsByOwner[player][i];
							var dist = (unit.position - position).sqrMagnitude;
							if (dist < minDist) {
								attackTarget = unit;
								minDist = dist;
							}
						}
					}

					if (attackTarget != null) {
						if (!weapon.InRangeOf(attackTarget.position)) {
							attackTarget = null;
						} else {
							if (weapon.Aim(attackTarget)) {
								weapon.Attack(attackTarget);
							}
						}
					}
				}

				if (attackTarget != null) {
					lastSeenAttackTarget = Time.time;
				}
			} else {
				rvo.locked = false | locked;

				// this.reachedDestination will be true once the AI has reached its destination
				// and it will stay true until the next time SetDestination is called.
				reachedDestination |= (ai as AIBase).rvoDensityBehavior.reachedDestination;

				if (weapon != null) {
					bool canAttack = movementMode == MovementMode.AttackMove;
					// This takes into account path calculations as well as if the AI stops far away from the destination due to being part of a large group
					canAttack |= reachedDestination && movementMode == MovementMode.Move;

					if (canAttack) {
						float minDist = detectionRange*detectionRange;

						Profiler.BeginSample("Distance");
						var pos = position;
						for (int player = 0; player < unitsByOwner.Length; player++) {
							if (!owner.IsHostile(RTSManager.instance.GetPlayer(player))) continue;

							var enemies = unitsByOwner[player];
							for (int i = 0; i < enemies.Count; i++) {
								var enemy = enemies[i];
								var dist = (enemy.position - pos).sqrMagnitude;
								if (dist < minDist) {
									attackTarget = enemy;
									minDist = dist;
								}
							}
						}
						Profiler.EndSample();

						float rangeFuzz = 1.1f;
						if (attackTarget != null && (attackTarget.position - position).magnitude > detectionRange*rangeFuzz) {
							attackTarget = null;
						}

						bool wantsToAttack = false;

						if (attackTarget != null) {
							if (!weapon.InRangeOf(attackTarget.position)) {
								ai.destination = attackTarget.position;
							} else {
								wantsToAttack = true;
								if (weapon.Aim(attackTarget)) {
									weapon.Attack(attackTarget);
								}
							}
						}

						if (attackTarget != null) {
							lastSeenAttackTarget = Time.time;
						}

						if (!weapon.canMoveWhileAttacking && (wantsToAttack || weapon.isAttacking)) {
							rvo.locked = true;
						}
					}
				}

				// Move back to original destination in case we followed an enemy for some time
				if (Time.time - lastSeenAttackTarget > 2) {
					ai.destination = lastDestination;
				}
			}
		}

		public void Die () {
			StartCoroutine(DieCoroutine());
		}

		IEnumerator DieCoroutine () {
			yield return new WaitForEndOfFrame();
			if (deathEffect != null) GameObject.Instantiate(deathEffect, transform.position, transform.rotation);
			GameObject.Destroy(gameObject);
		}

		public void ApplyDamage (float damage) {
			health = Mathf.Clamp(health - damage, 0, maxHealth);
			if (health <= 0) {
				Die();
			}
		}
	}
}