Created
September 12, 2012 23:34
-
-
Save Wikzo/3710770 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using UnityEngine; | |
public class TurretBarrel : MonoBehaviour | |
{ | |
public GameObject Projectile; | |
int h; | |
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