Created
December 19, 2017 06:46
-
-
Save Curookie/510af1997e3b65752afe3e902beb99e1 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.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class EnemyATTCtrl : MonoBehaviour { | |
public float timeBetweenAttacks = 0.5f; // The time in seconds between each attack. | |
public int attackDamage = 10; // The amount of health taken away per attack. | |
Animator anim; // Reference to the animator component. | |
GameObject player; // Reference to the player GameObject. | |
PlayerHPCtrl playerHealth; // Reference to the player's health. | |
//EnemyHealth enemyHealth; // Reference to this enemy's health. | |
bool playerInRange; // Whether player is within the trigger collider and can be attacked. | |
float timer; // Timer for counting up to the next attack. | |
void Awake() | |
{ | |
// Setting up the references. | |
player = GameObject.FindGameObjectWithTag("Player"); | |
playerHealth = player.GetComponent<PlayerHPCtrl>(); | |
// enemyHealth = GetComponent<EnemyHealth>(); | |
anim = GetComponent<Animator>(); | |
} | |
void OnTriggerEnter(Collider other) | |
{ | |
// If the entering collider is the player... | |
if (other.gameObject == player) | |
{ | |
// ... the player is in range. | |
playerInRange = true; | |
} | |
} | |
void OnTriggerExit(Collider other) | |
{ | |
// If the exiting collider is the player... | |
if (other.gameObject == player) | |
{ | |
// ... the player is no longer in range. | |
playerInRange = false; | |
} | |
} | |
void Update() | |
{ | |
// Add the time since Update was last called to the timer. | |
timer += Time.deltaTime; | |
// If the timer exceeds the time between attacks, the player is in range and this enemy is alive... | |
if (timer >= timeBetweenAttacks && playerInRange /*&& enemyHealth.currentHealth > 0*/) | |
{ | |
// ... attack. | |
Attack(); | |
} | |
// If the player has zero or less health... | |
if (playerHealth.currentHealth <= 0) | |
{ | |
// ... tell the animator the player is dead. | |
anim.SetTrigger("PlayerDead"); | |
} | |
} | |
void Attack() | |
{ | |
// Reset the timer. | |
timer = 0f; | |
// If the player has health to lose... | |
if (playerHealth.currentHealth > 0) | |
{ | |
// ... damage the player. | |
playerHealth.TakeDamage(attackDamage); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment