Drone.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. using System;
  2. using System.Collections;
  3. using UnityEngine;
  4. public class Drone : MonoBehaviour, ILaserable
  5. {
  6. /// <summary>
  7. /// The Drone's Health Points.
  8. /// </summary>
  9. [Tooltip("The Drone's Health Points.")]
  10. public int Hitpoints = 100;
  11. /// <summary>
  12. /// How long between each laser shot.
  13. /// </summary>
  14. [Tooltip("How long between each laser shot.e")]
  15. public float SecondsBetweenLaserShots = 4f;
  16. /// <summary>
  17. /// Accuracy of each shot. The laser will aim at a random point in a sphere around the user. This value sets that sphere's radius.
  18. /// </summary>
  19. [Tooltip("Accuracy of each shot. The laser will aim at a random point in a sphere around the user. This value sets that sphere's radius.")]
  20. public float laserAccuracy = 0.5f;
  21. /// <summary>
  22. /// The object spawned when the drone shoots.
  23. /// </summary>
  24. [Tooltip("The object spawned when the drone shoots.")]
  25. public GameObject LaserPrefab;
  26. /// <summary>
  27. /// The object that gets spawned when the drone dies. Intended to be an explosion.
  28. /// </summary>
  29. [Tooltip("The object that gets spawned when the drone dies. Intended to be an explosion.")]
  30. public GameObject ExplosionPrefab;
  31. /// <summary>
  32. /// How long it takes the drone to move to a new position.
  33. /// </summary>
  34. [Tooltip("How long it takes the drone to move to a new position.")]
  35. public float smoothTime = 0.75f;
  36. /// <summary>
  37. /// How far a potential movement point must be from real geometry to be considered valid .
  38. /// Set to higher values if the drone is moving into walls or other objects.
  39. /// </summary>
  40. [Tooltip("How far a potential movement point must be from real geometry to be considered valid. " +
  41. "Set to higher values if the drone is moving alongside walls or other objects. ")]
  42. public float ClearRadius = 2f;
  43. /// <summary>
  44. /// How many times we check near a potential movement point to see if there are any obstacles around it.
  45. /// Higher values make it less likely a drone will move inside an object, but may cause noticeable stutter.
  46. /// </summary>
  47. [Tooltip("How many times we check near a potential movement point to see if there are any obstacles around it. " +
  48. "Higher values make it less likely a drone will move inside an object, but may cause noticeable stutter.")]
  49. public int radiusCheckRate = 100;
  50. /// <summary>
  51. /// The maximum amount of collisions detected near a movement point allowed.
  52. /// Higher values make it less likely for a drone to move inside an object, but too high and it may not move at all.
  53. /// </summary>
  54. [Tooltip("The maximum amount of collisions detected near a movement point allowed. " +
  55. "Higher values make it less likely for a drone to move inside an object, but too high and it may not move at all.")]
  56. public float percentageThreshold = 0.35f;
  57. /// <summary>
  58. /// Maximum angle between drone and its target to have before the drone will turn to face it.
  59. /// </summary>
  60. [Tooltip("Maximum angle between drone and its target to have before the drone will turn to face it.")]
  61. public float angleBeforeRotate = 20f;
  62. /// <summary>
  63. /// "AudioClips to play for the Drone. Element 0 is for its laser, 1 is for its destruction."
  64. /// </summary>
  65. [Tooltip("AudioClips to play for the Drone. Element 0 is for its laser, 1 is for its destruction.")]
  66. public AudioClip[] clips;
  67. /// <summary>
  68. /// Counts down the time between shots.
  69. /// </summary>
  70. private float lasershottimer;
  71. /// <summary>
  72. /// What the drone is looking/shooting at.
  73. /// </summary>
  74. private Transform target;
  75. /// <summary>
  76. /// The gun's target to rotate towards.
  77. /// </summary>
  78. private Vector3 guntarget;
  79. /// <summary>
  80. /// Reference to the audio source.
  81. /// </summary>
  82. private AudioSource audiosource;
  83. /// <summary>
  84. /// Main ZEDManager to use for determining where the drone spawns and what it attacks.
  85. /// If left empty, will choose the first available ZEDManager in the scene.
  86. /// </summary>
  87. [Tooltip("Main ZEDManager to use for determining where the drone spawns and what it attacks. " +
  88. "If left empty, will choose the first available ZEDManager in the scene. ")]
  89. public ZEDManager zedManager = null;
  90. /// <summary>
  91. /// The Mesh Renderer of the drone, so we can modify its material when it takes damage.
  92. /// </summary>
  93. private Renderer meshrenderer;
  94. /// <summary>
  95. /// FX for when we take damage.
  96. /// </summary>
  97. private Transform damagefx;
  98. /// <summary>
  99. /// Where we shoot the laser from.
  100. /// </summary>
  101. private Transform laseranchor;
  102. /// <summary>
  103. /// FX for when we shoot.
  104. /// </summary>
  105. private ParticleSystem muzzleflashfx;
  106. /// <summary>
  107. /// The bone that moves the drone's gun.
  108. /// </summary>
  109. private Transform dronearm;
  110. /// <summary>
  111. /// The next position that the drone needs to move to. Set only after a valid move location has been confirmed.
  112. /// </summary>
  113. private Vector3 nextposition;
  114. /// <summary>
  115. /// A reference for the SmoothDamp of the drone's movement.
  116. /// </summary>
  117. private Vector3 velocity = Vector3.zero;
  118. /// <summary>
  119. /// The light to be enabled briefly when the drone has fired.
  120. /// </summary>
  121. private Light gunlight;
  122. /// <summary>
  123. /// Whether or not we can rotate towards our target.
  124. /// </summary>
  125. private bool canrotate = false;
  126. /// <summary>
  127. /// Are we moving the drone or not.
  128. /// </summary>
  129. private bool canchangerotation = false;
  130. /// <summary>
  131. /// Link with the object that spawned this instance. Used to clear the spawner's reference in OnDestroy().
  132. /// </summary>
  133. private DroneSpawner spawner;
  134. private float damageFlashAmount
  135. {
  136. #if !ZED_HDRP || !ZED_URP
  137. get
  138. {
  139. return meshrenderer.material.GetColor("_Color").a;
  140. }
  141. set
  142. {
  143. Color newcol = meshrenderer.material.GetColor("_Color");
  144. newcol.a = value;
  145. meshrenderer.material.SetColor("_Color", newcol);
  146. }
  147. #elif ZED_HDRP
  148. get
  149. {
  150. return meshrenderer.material.GetColor("_BaseColor").a;
  151. }
  152. set
  153. {
  154. Color newcol = meshrenderer.material.GetColor("_BaseColor");
  155. newcol.a = value;
  156. meshrenderer.material.SetColor("_BaseColor", newcol);
  157. }
  158. #elif ZED_URP
  159. get
  160. {
  161. return meshrenderer.material.GetColor("_BaseColor").a;
  162. }
  163. set
  164. {
  165. Color newcol = meshrenderer.material.GetColor("_BaseColor");
  166. newcol.a = value;
  167. meshrenderer.material.SetColor("_BaseColor", newcol);
  168. }
  169. #endif
  170. }
  171. // Use this for initialization
  172. void Start ()
  173. {
  174. //Cache the ZED's left camera for occlusion testing purposes
  175. if (zedManager==null)
  176. zedManager = FindObjectOfType<ZEDManager>();
  177. // Set the default position of the Drone to the one he spawned at.
  178. nextposition = transform.position;
  179. //Set the countdown timer to fire a laser
  180. lasershottimer = SecondsBetweenLaserShots;
  181. // Set the audio source.
  182. audiosource = GetComponent<AudioSource>();
  183. if(audiosource != null && clips.Length > 2)
  184. {
  185. audiosource.clip = clips[2];
  186. audiosource.volume = 1f;
  187. audiosource.Play();
  188. }
  189. // If these variables aren't set, look for their objects by their default name.
  190. Transform[] children = transform.GetComponentsInChildren<Transform>();
  191. foreach (var child in children) {
  192. if (child.name == "Drone_Mesh")
  193. meshrenderer = child.GetComponent<Renderer>();
  194. else if (child.name == "MuzzleFlash_FX")
  195. muzzleflashfx = child.GetComponent<ParticleSystem>();
  196. else if (child.name == "Damage_FX")
  197. damagefx = child;
  198. else if (child.name == "Laser_Anchor")
  199. laseranchor = child;
  200. else if (child.name == "Gun_Arm")
  201. dronearm = child;
  202. else if (child.name == "Point_Light")
  203. gunlight = child.GetComponent<Light>();
  204. }
  205. //If the _target isn't set, set it to the PlayerDamageReceiver, assuming there is one in the scene.
  206. if(!target)
  207. {
  208. target = FindObjectOfType<PlayerDamageReceiver>().transform;
  209. guntarget = target.position;
  210. }
  211. }
  212. void Update ()
  213. {
  214. //If we've flashed the damage material, lower the blend amount.
  215. if (damageFlashAmount > 0)
  216. {
  217. float tmp = damageFlashAmount;
  218. tmp -= Time.deltaTime / 1.5f;
  219. if (tmp < 0)
  220. tmp = 0;
  221. damageFlashAmount = tmp;
  222. }
  223. //Enabling damage FX based on HitPoints left.
  224. switch (Hitpoints) {
  225. case 80:
  226. damagefx.GetChild (0).gameObject.SetActive (true);
  227. break;
  228. case 50:
  229. damagefx.GetChild (1).gameObject.SetActive (true);
  230. break;
  231. case 20:
  232. damagefx.GetChild (2).gameObject.SetActive (true);
  233. break;
  234. }
  235. //If its time to can change our position...
  236. if (canchangerotation)
  237. {
  238. //...then look for a new one until it's a valid location.
  239. if (FindNewMovePosition (out nextposition))
  240. {
  241. canchangerotation = false;
  242. }
  243. }
  244. //Count down the laser shot timer. If zero, fire and reset it.
  245. lasershottimer -= Time.deltaTime;
  246. if (lasershottimer <= 0f && target != null)
  247. {
  248. //Apply a degree of accuracy based on the drone distance from the player
  249. //Take a random point on a radius around the Target's position. That radius becomes smaller as the target is closer to us.
  250. Vector3 randompoint = UnityEngine.Random.onUnitSphere * (laserAccuracy * (Vector3.Distance(target.position, transform.position) / (spawner.maxSpawnDistance / 2))) + target.position;
  251. //Check if the chosen point is closer to the edge of the camera. We dont want any projectile coming straight in the players eyes.
  252. if (randompoint.z >= target.position.z + 0.15f || randompoint.z <= target.position.z - 0.15f)
  253. {
  254. guntarget = randompoint;
  255. //Firing the laser
  256. FireLaser(randompoint);
  257. //Reseting the timer.
  258. lasershottimer = SecondsBetweenLaserShots;
  259. }
  260. }
  261. //Drone Movement & Rotation
  262. if (target != null)
  263. {
  264. //Get the direction to the target.
  265. Vector3 targetDir = target.position - transform.position;
  266. //Get the angle between the drone and the target.
  267. float angle = Vector3.Angle(targetDir, transform.forward);
  268. //Turn the drone to face the target if the angle between them if greater than...
  269. if (angle > angleBeforeRotate && canrotate == false)
  270. {
  271. canrotate = true;
  272. }
  273. if (canrotate == true) {
  274. var newRot = Quaternion.LookRotation (target.transform.position - transform.position);
  275. transform.rotation = Quaternion.Lerp (transform.rotation, newRot, Time.deltaTime * 2f);
  276. if (angle < 5 && canrotate == true)
  277. {
  278. canrotate = false;
  279. }
  280. }
  281. //Rotate the drone's gun to always face the target.
  282. dronearm.rotation = Quaternion.LookRotation (guntarget - dronearm.position);
  283. }
  284. //Simply moving nextposition to something other than transform.position will cause it to move.
  285. if (transform.position != nextposition)
  286. {
  287. transform.position = Vector3.SmoothDamp(transform.position, nextposition, ref velocity, smoothTime);
  288. }
  289. }
  290. /// <summary>
  291. /// Fires the laser.
  292. /// </summary>
  293. private void FireLaser(Vector3 randompoint)
  294. {
  295. if (audiosource.clip != clips[0])
  296. {
  297. audiosource.clip = clips[0];
  298. audiosource.volume = 0.2f;
  299. }
  300. //Creat a laser object
  301. GameObject laser = Instantiate(LaserPrefab);
  302. laser.transform.position = laseranchor.transform.position;
  303. laser.transform.rotation = Quaternion.LookRotation(randompoint - laseranchor.transform.position);
  304. //Play the Particle effect.
  305. muzzleflashfx.Play();
  306. //Play a sound
  307. if (audiosource)
  308. {
  309. audiosource.Play();
  310. }
  311. //MuzzleFlashLight
  312. StartCoroutine(FireLight());
  313. //StartRelocatingDrone
  314. StartCoroutine(RelocationDelay());
  315. }
  316. /// <summary>
  317. /// Forces a delay before moving, and then only allows rotation if the drone has reached its destination.
  318. /// </summary>
  319. /// <returns></returns>
  320. IEnumerator RelocationDelay()
  321. {
  322. yield return new WaitForSeconds(1f);
  323. //Allow another relocation if we have already reached the current nextposition.
  324. if (Vector3.Distance(transform.position, nextposition) <= 0.1f)
  325. {
  326. canchangerotation = true;
  327. }
  328. }
  329. /// <summary>
  330. /// What happens when the drone gets damaged. In the ZED drone demo, Lasershot_Player calls this.
  331. /// </summary>
  332. /// <param name="damage">Damage.</param>
  333. void ILaserable.TakeDamage(int damage)
  334. {
  335. //Remove hitpoints as needed
  336. Hitpoints -= damage;
  337. //Blend the materials to make it take damage
  338. //meshrenderer.material.SetFloat("_Blend", 1);
  339. damageFlashAmount = 1f;
  340. //Destroy if it's health is below zero
  341. if (Hitpoints <= 0)
  342. {
  343. //Add time to prevent laser firing while we die.
  344. lasershottimer = 99f;
  345. if(spawner) spawner.ClearDrone();
  346. if (ExplosionPrefab)
  347. {
  348. Instantiate(ExplosionPrefab, transform.position, Quaternion.identity);
  349. }
  350. if (audiosource != null && clips.Length > 1)
  351. {
  352. audiosource.Stop();
  353. audiosource.clip = clips[1];
  354. audiosource.volume = 1f;
  355. audiosource.Play();
  356. }
  357. StartCoroutine(DestroyDrone());
  358. return;
  359. }
  360. }
  361. /// <summary>
  362. /// Plays explosion FX, then destroys the drone.
  363. /// </summary>
  364. /// <returns></returns>
  365. IEnumerator DestroyDrone()
  366. {
  367. transform.GetChild(0).gameObject.SetActive(false);
  368. transform.GetChild(1).gameObject.SetActive(false);
  369. yield return new WaitForSeconds(3f);
  370. Destroy(gameObject);
  371. }
  372. /// <summary>
  373. /// Checks nearby for valid places for the drone to move.
  374. /// Valid places must be in front of the player, and not intersect any objects within a reasonable tolerance.
  375. /// Use radiusCheckRate and percentageThreshold to tweak what counts as a valid location.
  376. /// </summary>
  377. /// <param name="newpos"></param>
  378. /// <returns></returns>
  379. private bool FindNewMovePosition(out Vector3 newpos)
  380. {
  381. //We can't move if the ZED isn't initialized.
  382. if (!zedManager.IsZEDReady)
  383. {
  384. newpos = transform.position;
  385. return false;
  386. }
  387. Vector3 randomPosition;
  388. // Look Around For a New Position
  389. //If the Drone is on the screen, search around a smaller radius.
  390. //Note that we only check the primary ZEDManager because we only want the drone to spawn in front of the player anyway.
  391. if (ZEDSupportFunctions.CheckScreenView(transform.position, zedManager.GetMainCamera()))
  392. randomPosition = UnityEngine.Random.onUnitSphere * UnityEngine.Random.Range(2f, 3f) + transform.position;
  393. else //if the drone is outside, look around a bigger radius to find a position which is inside the screen.
  394. randomPosition = UnityEngine.Random.onUnitSphere * UnityEngine.Random.Range(4f, 5f) + transform.position;
  395. // Look For Any Collisions Through The ZED
  396. bool hit = ZEDSupportFunctions.HitTestAtPoint(zedManager.zedCamera, zedManager.GetMainCamera(), randomPosition);
  397. if (!hit)
  398. {
  399. newpos = transform.position;
  400. return false;
  401. }
  402. //If we spawn the drone at that world point, it'll spawn inside a wall. Bring it closer by a distance of ClearRadius.
  403. Quaternion directiontoDrone = Quaternion.LookRotation(zedManager.GetMainCameraTransform().position - randomPosition, Vector3.up);
  404. Vector3 newPosition = randomPosition + directiontoDrone * Vector3.forward * ClearRadius;
  405. //Check the new position isn't too close from the camera.
  406. float dist = Vector3.Distance(zedManager.GetMainCamera().transform.position, randomPosition);
  407. if (dist < 1f)
  408. {
  409. newpos = transform.position;
  410. return false;
  411. }
  412. //Also check nearby points in a sphere of radius to make sure the whole drone has a clear space.
  413. if (ZEDSupportFunctions.HitTestOnSphere(zedManager.zedCamera, zedManager.GetMainCamera(), newPosition, 1f, radiusCheckRate, percentageThreshold))
  414. {
  415. newpos = transform.position;
  416. return false;
  417. }
  418. //Return true if it's made it this far and out the location we chose.
  419. newpos = newPosition;
  420. return true;
  421. }
  422. /// <summary>
  423. /// Sets a reference to the Drone spawner governing its spawning.
  424. /// Used to notify the spawner when it's destroyed.
  425. /// </summary>
  426. /// <param name="spawner">Reference to the scene's DroneSpawner component.</param>
  427. public void SetMySpawner(DroneSpawner spawner)
  428. {
  429. this.spawner = spawner;
  430. }
  431. /// <summary>
  432. /// Turns on the drone gun's light briefly to simulate a muzzle flash. Because lasers totally have muzzle flashes.
  433. /// </summary>
  434. /// <returns></returns>
  435. IEnumerator FireLight()
  436. {
  437. gunlight.enabled = true;
  438. yield return new WaitForSeconds(0.15f);
  439. gunlight.enabled = false;
  440. }
  441. }