Now that we have enemies moving towards us, we need some way for them to be damaged and killed! Let's do that now by performing the following steps:
Enemy
into Element 0. Ghost
:PhoneBehaviour
script and add the following code in bold to its Update
function:// Update is called once per frame void Update () { // Are we holding down the right mouse button if (Input.GetMouseButton(1) && !cameraActive) { SetCameraActive(true); } else if(cameraActive && !Input.GetMouseButton(1)) { SetCameraActive(false); } if (cameraActive && Input.GetMouseButton(0)) { StartCoroutine(CameraFlash()); GameObject[] enemyList = GameObject.FindGameObjectsWithTag("Enemy"); foreach (GameObject enemy in enemyList) { if (enemy.activeInHierarchy) { EnemyBehaviour behaviour = enemy.GetComponent<EnemyBehaviour>(); behaviour.TakeDamage(); } } }
Now that we say there is a TakeDamage
function in our EnemyBehaviour
class, we need to add that in. Open the EnemyBehaviour
class, and first, we need to create some variables as follows:
public float health = 100.0f; private float currentHealth;
currentHealth
, so add the following code in bold to the Start
function:void Start () { GoToNextState(); currentHealth = health ; }
TakeDamage
function, as follows:public void TakeDamage() { // The closer I am, the more damage I do float damageToDo = 100.0f - (GetDistance () * 5); if (damageToDo < 0) damageToDo = 0; if (damageToDo > health) damageToDo = health; currentHealth -= damageToDo; if(currentHealth <= 0) { state = State.Die; } else { // If we're not dead, now that we took a picture the // enemy // knows where we are followRange = Mathf.Max(GetDistance(), followRange); state = State.Follow; } print ("Ow! - Current Health: " + currentHealth.ToString()); }
Now, the enemy will follow you when you take its picture and the closer you are to it, the more it will get damaged, which you can see by looking at the console!