- Home /
"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;
}
You can see the AI.js script in the FPS tutorial if you haven't checked it out yet. Its available on the Unity website, it does exactly the thing that you want and also can be expanded easily for other features you might want to add later to the AI.
Have you written the Gizmo code, in the first place? To place the waypoints?
Answer by KazeEnji · Jan 23, 2012 at 01:51 PM
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-
Thank you. I will try what you and Vatsal said. Hopefully it will work. Thanks again!
Your answer
Follow this Question
Related Questions
Freelancer of Freespace type Enemy Ai 2 Answers
WayPoints mixed with Raycast 1 Answer
Trying to make AI travel (and face) a waypoint 0 Answers
Way Point Script Change Group 0 Answers
Why isn't a Ai Waypoint Spawning??? 0 Answers