"AI"/Behaviour for a Waypoint system

Hey!

Just like the name implies, i need some help scrpiting some “Ai”. Me and a few of my friends is creating a space shooter game, sort of like Star Fox, and we have the basic elements done, except for enemy behaviours.
What i want the enemy to do is basically this: When the player is in reach, the enemy will chase the player while firing. When the player is out of their reach, they return to their waypoint patrolling.

So, have you guys got any ideas? This is the waypoint code i use at the moment.

var waypoint : Transform[];
var speed : float = 20;
private var currentWaypoint : int;
var loop : boolean = true;

function Update(){
if(currentWaypoint < waypoint.length){
var target : Vector3 = waypoint[currentWaypoint].position;
var moveDirection : Vector3 = target - transform.position;
var velocity = rigidbody.velocity;

transform.LookAt(target);
if(moveDirection.magnitude < 1){
currentWaypoint++;
}

else {
velocity = moveDirection.normalized * speed;
}
}
else {
if (loop){
currentWaypoint=0;
}
else{
velocity = Vector3.zero;
}
}
rigidbody.velocity = velocity;
}

For the part where you want them to chase the player when they’re in range; you could always use a large sphere collider/trigger. Just make the sphere as large as you want your AI’s “sight” to be and make a script that is just an OnTriggerEnter.

Pseudocode:

if(collision detected with tag "player")
     addForce to enemy and chase player *or you could use move towards if you don't want physics invloved*
    if(player no longer detected)
         Continue moving in last known direction for 5 seconds just because
         Still no player? Return to waypoint script.

Now, you’re likely going to run into a problem if you use a trigger event not reactivating if the player passes in a second time. I think when I ran into that problem I used either a disable/enable kind of loop on the Trigger script, or I did a tagging system that referenced the tag on the sphere collider instead of the collider itself…

Hope this helps point you in the right direction.

Later!
-Kaze-