- Home /
Attack speed
I have my ai setup but am confused on how to setup my timer to not keep repeating itself.
Right now it's setup so if the enemy is within a certain distance of the player it deals damage everytime the update function is called. How would I make it so once the player is within the attack range of an enemy that it starts a timer and then when the timers up it deals damage unless the player exceeds the distance which would stop the timer.
If I made it so the timer is called constantly when the player is in range it would be a big mess of the same timer being called a ton of times.
Answer by Bunny83 · May 26, 2011 at 01:14 PM
Well i would use a timeout value when the next attack will happen.
Something like:
var attackDelay = 1.0f;
private var nextDamageEvent : float;
function Update()
{
if ($PlayerIsInRange$)
{
if (Time.time >= nextDamageEvent)
{
nextDamageEvent = Time.time + attackDelay;
// Do damage here
}
}
else
{
nextDamageEvent = Time.time + attackDelay;
}
}
I guess you mean line 16?
Well, when the condition "player is in range" is false we constantly reset the timer. That prevents the enemy from immediately attacking once in range. If you need it or not depends on your desired behaviour.