- Home /
I am trying to make my enemy AI have an attack delay
right now my enemy AI attacks the player when in range but when it attacks it doesn't have a delay I've tried many different things to find an answer but none seem to work can someone help? My code given is being called by the void OnTriggerStay so it attacks each time the player is in the collider is there a way to add an attack delay to the enemies attack with the code i have given?
void OnTriggerStay(Collider other) { if (other.gameObject == player) {
Attack();
} }
' private void Attack() //Call this in OnTriggerStay if the colliding gameObject is the player { anim.SetTrigger("Attack"); //trigger our animation
if (playerHealth.currentHealth > 0)
{
playerHealth.TakeDamage(attackDamage); //make player take damage
}
if (Time.time > attackDelay)//Check if current game time is at or past the time we last set
{
attackDelay = Time.time + attackRate; //Set timer to current game time plus our delay.
}
}
Answer by the_genius · Apr 30, 2018 at 01:00 PM
The last few lines of your code are changing the value of the 'attackDelay' variable but doing nothing with it that causes a delay. You need to remember the value of Time.time when the enemy last attacked (call it lastAttacked) and only attack again if Time.time has increased above lastAttacked+attackDelay.
public float attackDelay = 100;
float lastAttacked = -9999;
void OnTriggerStay(Collider other) {
if (other.gameObject == player) {
Attack();
}
}
private void Attack() { //Call this in OnTriggerStay if the colliding gameObject is the player
if (Time.time > lastAttacked + attackDelay) {
anim.SetTrigger("Attack"); // trigger our animation
if (playerHealth.currentHealth > 0)
{
playerHealth.TakeDamage(attackDamage); //make player take damage
}
lastAttacked = Time.time;
}
}
Your answer
Follow this Question
Related Questions
Enemy AI problems 2 Answers
delay first spawn 2 Answers
How to make an enemy respawn? 0 Answers
I need help making my enemy AI have an attack delay 2 Answers
Shoot Bullet Delay Enemy 0 Answers