Guest User

Untitled

a guest
Feb 19th, 2017
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class Turret : MonoBehaviour {
  6.  
  7. private Transform target;
  8. private Enemy targetEnemy;
  9.  
  10. [Header("Attributes")]
  11.  
  12. public float range = 15f;
  13. public float fireRate = 1f;
  14. private float fireCountdown = 0f;
  15.  
  16. [Header("Unity Setup Fields")]
  17.  
  18. public string enemyTag = "Enemy";
  19.  
  20.  
  21. public Transform partToRotate;
  22. public float turnSpeed = 10f;
  23.  
  24. public GameObject bulletPrefab;
  25. public Transform firePoint;
  26.  
  27.  
  28.  
  29. // Use this for initialization
  30. void Start () {
  31. InvokeRepeating("UpdateTarget", 0f, 0.5f);
  32. }
  33.  
  34. void UpdateTarget ()
  35. {
  36. GameObject[] enemies = GameObject.FindGameObjectsWithTag(enemyTag);
  37. float shortestDistance = Mathf.Infinity;
  38. GameObject nearestEnemy = null;
  39. foreach (GameObject enemy in enemies)
  40. {
  41. float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);
  42. if (distanceToEnemy < shortestDistance)
  43. {
  44. shortestDistance = distanceToEnemy;
  45. nearestEnemy = enemy;
  46. }
  47. }
  48.  
  49. if (nearestEnemy != null && shortestDistance <= range)
  50. {
  51. target = nearestEnemy.transform;
  52. targetEnemy = nearestEnemy.GetComponent<Enemy>();
  53. } else
  54. {
  55. target = null;
  56. }
  57.  
  58. }
  59.  
  60.  
  61. // Update is called once per frame
  62. void Update () {
  63. if (target == null)
  64. return;
  65.  
  66. //Target lock on
  67. Vector3 dir = target.position - transform.position;
  68. Quaternion lookRotation = Quaternion.LookRotation(dir);
  69. Vector3 rotation = Quaternion.Lerp(partToRotate.rotation, lookRotation, Time.deltaTime * turnSpeed).eulerAngles;
  70. partToRotate.rotation = Quaternion.Euler(0f, rotation.y, 0f);
  71.  
  72. if (fireCountdown <= 0f)
  73. {
  74. Shoot();
  75. fireCountdown = 1f / fireRate;
  76. }
  77.  
  78. fireCountdown -= Time.deltaTime;
  79.  
  80.  
  81.  
  82.  
  83. }
  84.  
  85. void Shoot ()
  86. {
  87. GameObject bulletGO = (GameObject)Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
  88. Bullet bullet = bulletGO.GetComponent<Bullet>();
  89.  
  90. if (bullet != null)
  91. bullet.Seek(target);
  92. }
  93.  
  94. void OnDrawGizmosSelected ()
  95. {
  96. Gizmos.color = Color.red;
  97. Gizmos.DrawWireSphere(transform.position, range);
  98. }
  99. }
Add Comment
Please, Sign In to add comment