Ideally you should use states. Your enemy would have a list [COLOR=blue][COLOR=blue][COLOR=blue][COLOR=blue]of[/COLOR][/COLOR][/COLOR][/COLOR] states, which one with a certain behavior, triggers would set the enemy’s current state. For instance:
onEnterFrame = function() {
distance = player._x - evilGuy._x;
switch(enemyState){
case 'fire':
//Enemy fires, include here all code related to firing.
enemyState = 'follow';
break;
case 'flee':
if (distance <= safeDistance) {
evilGuy._x -= speed * distance / Math.abs(distance);
} else {
enemyState = 'fire';
}
break;
case 'follow':
evilGuy._x += speed * distance / Math.abs(distance);
break;
}
}
First a small intro on the switch clause as many people doesn’t use it. It checks for the value [COLOR=blue][COLOR=blue]of[/COLOR][/COLOR] the variable between brackets and it has a list [COLOR=blue][COLOR=blue]of[/COLOR][/COLOR] possible values (cases) and what to do for each [COLOR=blue][COLOR=blue]of[/COLOR][/COLOR] those values. everything between ‘case <casename>:’ and ‘break;’ is executed in case the value [COLOR=blue][COLOR=blue]of[/COLOR][/COLOR] that variable matches <casename>.
Now, to our states… By default, enemy’s state would be ‘follow’, when the trigger is activated (let’s say, it gets hit), it would be set to ‘flee’. In flee mode, as you can see, it checks for the distance between him and the player, if it’s lower than the safeDistance variable (you can set it beforehand to any value you like), he will try to run away, otherwise his state is set to ‘fire’, making him fire once and seting it back to ‘follow’.
We could include the “face back and fire” stuff into the flee behavior, but I thought you might want to order the enemy to fire once in a while, independent [COLOR=blue][COLOR=blue][COLOR=blue][COLOR=blue]of[/COLOR][/COLOR][/COLOR][/COLOR] it fleeing or not, so I kept both as independent states.
The point is: you want it to fire, use enemyState = ‘fire’; want it to run, enemyState = ‘flee’; want it to chase the player, enemyState = ‘follow’. You can list other behaviors like ‘patrol’, ‘hide’, etc, define what the enemy is suppose to do in that case and just set the state variable (enemyState) when the right condition is triggered.
Is it clear? Let me know if you need further help.