- Home /
Add wait time to enemy's attack
Here is the code I made for the enemy's attack. This function is called by another script (in C#) using SendMessage("Attack");
function Attack() { yield WaitForSeconds(attackLag); var myself : EnemyDamage = GetComponent(EnemyDamage);
if (!myself.flinch)
{
// Keep looking if we are hitting our target
// If we are, knock them out of the way, dealing damage
Debug.Log("I'm Attacking");
animation.Play("punch");
var pos = transform.TransformPoint(punchPosition);
if(Time.time > lastPunchTime + 4 && (pos - target.position).magnitude < punchRadius)
{
// deal damage
target.SendMessage("ApplyDamage", damage);
// knock the player back and to the side
var slamDirection = transform.InverseTransformDirection(target.position - transform.position);
slamDirection.y = 0;
slamDirection.z = strength;
if (slamDirection.x >= 0)
slamDirection.x = 0.1;
else
slamDirection.x = -0.1;
target.SendMessage("Slam", transform.TransformDirection(slamDirection));
lastPunchTime = Time.time;
}
}
}
I tried using yield WaitForSeconds, but it only lags the first attack, then the next few are consecutive. What should I do?
Answer by StephanK · Nov 03, 2010 at 08:30 AM
I guess the problem is that you are calling Attack in rapid succession. So the effect you'd see is that the first call gets delayed and all others get called immediately after the first one.
What you need to do is using Attack as a Coroutine with a while loop inside. So you could transform your code into something like this (this should only give you an idea, it will not work as is):
function Attack() {
while ((pos - target.position).magnitude < punchRadius) {
target.SendMessage("ApplyDamage", damage);
yield WaitForSeconds(attackLag);
}
}
Be aware that you have to call this routine only ONCE to start attacking. It will then continue to attack the target until it's out of range. So probably you'll also need a check if target died.
I tried using this method with my current logic, but I end up hitting hit like 4 times after the lag.
$$anonymous$$ake sure you're calling Attack() only once to start attacking. $$anonymous$$aybe you can post your current logic?
Answer by zannghast · Nov 03, 2010 at 08:46 AM
An alternate solution would be to 'deactivate' function 'Attack()' by setting a state in the beginning and end.
Such as:
// global variable var attacking : bool = false;
function Attack() {
if (!attacking) {
attacking = true;
...
//rest of the code
...
attacking = false;
}
}
If I'm not mistaken, attacking would only be set to false only after attacklag seconds has passed.
Your answer
Follow this Question
Related Questions
Why is this script causing a lot of lag? 2 Answers
Problem getting AI to wait 1 Answer
How to make an object jump? 0 Answers
switch prefab on collision 1 Answer