In this tutorial we are going to go through the process a making sentry turrets. Between tutorial 1 and this one, I made a simple script to spawn monster prefabs – I figured no need for me to cover this as this is much better covered other places.
Like the last one, here is the youtube video of the tutorial:
Below is the important script portion.
Here is the TurretController Script, attached to the turret prefab:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TurretController : MonoBehaviour { // reference to bullet prefab public GameObject bulletPreFab; // firing rate s/projectile public float fireRate = .01f; public float fireCooldown = 0f; // holds all monsters that are in range List<GameObject> inRangeMonsters = new List<GameObject>(); void Start() { } // Update is called once per frame void Update() { // if there are monsters in range if(inRangeMonsters.Count > 0) { fireCooldown += Time.deltaTime; while (fireCooldown >= fireRate) { FireProjectile(inRangeMonsters[0]); fireCooldown -= fireRate; } } } private void OnTriggerEnter2D(Collider2D collision) { // get game object GameObject go = collision.gameObject; // we only want to fire at monsters if (go.CompareTag("Monster")) { // add monster to list inRangeMonsters.Add(go); } } private void OnTriggerExit2D(Collider2D collision) { // get game object GameObject go = collision.gameObject; // if they get out of range or die if (go.CompareTag("Monster")) { // remove from list inRangeMonsters.Remove(go); } } private void FireProjectile(GameObject targetObject) { // create the new bullet GameObject newObject = Instantiate(bulletPreFab); // setting starting position of bullet at turret newObject.transform.position = this.transform.position; // direction to shoot (target object - turret) Vector2 trajectory = (Vector2)targetObject.transform.position - (Vector2)this.transform.position; // give trajectory to object newObject.GetComponent<BulletController>().SetTrajectory(trajectory); // convertering trajectory into rotation angle and setting float angle = Mathf.Atan2(trajectory.y, trajectory.x) * 360f / (2f * Mathf.PI) - 90f; // rotate turret this.transform.rotation = Quaternion.Euler(0f, 0f, angle); } }
The turret pre-fab also needs a CircleCollider2d attached to it to simulate eye-sight/range. The collider will need to be marked as “Is Trigger” to allow the monster objects to pass through and trigger the functions. Additionally, set the radius of the collider to the desired range by modifying the Radius.