Skip to content

Instantly share code, notes, and snippets.

@Wikzo
Created September 12, 2012 23:33
Show Gist options
  • Save Wikzo/3710763 to your computer and use it in GitHub Desktop.
Save Wikzo/3710763 to your computer and use it in GitHub Desktop.
using System;
using UnityEngine;
public class TurretBarrel : MonoBehaviour
{
public GameObject Projectile;
public float AttackRange = 25f; // Distance
public float AttackDelay = 1f; // Time
public bool IsAlive { get; set; }
private GameObject _player;
private float _attackTimer;
public void Start()
{
_player = GameObject.Find("PlayerShip");
if (_player == null)
throw new InvalidOperationException("Player was not found by TurretBarrel");
_attackTimer = 0;
IsAlive = false;
}
public void Update()
{
if (!IsAlive)
return;
if (CanFire())
Fire();
else
{
_attackTimer -= Time.deltaTime;
}
}
private bool CanFire()
{
// Within range of player?
return Vector3.Distance(_player.transform.position, transform.position) <= AttackRange && _attackTimer <= 0f;
}
private void Fire()
{
// Notes about the static Instantiate method:
// System.Object is the same as Object
// UnityEngine.Object is NOT the same
_attackTimer = AttackDelay;
var prefab = (GameObject)Instantiate(Projectile, transform.position, transform.rotation); // Instantiate is the same as GameObject.Instantiate
prefab.transform.localScale = transform.localScale;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment