AI Guard Unit
by Mark Holcomb · 11/27/2004 (5:18 pm) · 335 comments
Download Code File
This is my second attempt at making an AI controlled character. The first was an
AIPlayer that would follow paths. This character is a guard unit. The guard will
wait at it's post (spawn point) until it sees a target. It will then attack that
target while trying to close with it.
If the target is lost the bot will wait at the last place it saw the character and
look around for a little bit, and then it will try to return to it's post.
There is a chance the bot will get stuck trying to return, but there is a simple
routine that has the bot try to move in random directions to try and clear itself
of any obstacles between it and it's post. It's not perfect.
The thinking routine is a simple state machine - which can be expanded on to give the bot more responses and actions.
As with my first ai character, I am using a simple system that allows the designer to drop
markers in the game map that will mark where the bots will start out. When the mission is loaded, the markers are detected and bots are spawned at the marker locations. The markers are then hidden from view. (The markers can be left visible to help in map editing.)
The markers for the guards can be given a dynamic variable called respawn. (Assigned to the marker during map editing.) 'Respawn' will determine whether a bot respawns or not upon death.
The bots have an attention setting. How often they scan is determined by their attention level. The bots get more sluggish (freeing up processor time) when targets are too far away. Conversely, the bot becomes incrementally more attentive as targets come within range, and further aware as targets come into sight.
When a target is found in range and in sight the bot will shoot at the target. The firing sequence is a step of scheduled calls that call for a firing cycle, a trigger down cycle, and a firing delay to control bot rate of fire.
When a bot is attacked it will attempt to sideatep and it's field of vision is temporarily increased to a 360deg field of vision - to emulate looking around to see what happened. The bot's attention level is also set to make it think at it's fastest rate when attacked.
To use the AIGuard...the following changes need to be made.
1. Back up your original game.cs, player.cs, and your current build of Torque. To install AIGuard will require a recompile, since I have created a new class cloned by copying AIPlayer.cc and AIPlayer.h and renaming all references to AIPlayer to AIGuard.
(I did this because I wanted to be able to run both my AIPatroller and AIGuards in the same maps and did not want to have any confusion between them.)
2. Add the files AIGuard.cc and AIGuard.h to your Torque project. (In my instance I saved them to my c:\Torque\engine\game directory and then added them into my project.)
3. Recompile your project and copy your new executable to the appropriate directory for your app.
4. Copy the file AIGuard.cs into your server/scripts directory.
5. Modify game.cs to add the line
to the function onServerCreated().
6. Also in game.cs: The section for function StartGame needs to modified the following ways:
Below the lines that read:
add this:
(If you followed my previous resource you may not have any reference to AImanager. Don't fret... just look for the place in game.cs where you have
and put in
right underneath it.
7. In player.cs in the code for Armor::Damage modify the lines
to read:
*** If you followed my previous resource there should be no need to change this code.
8. Load your map - Stronghold as an example.
9. Go into the map editor. (F11) Then go into the Editor Creator (F4)
10. Under Shapes there should be a drop down called AIMarker, under that a new item called AIGuard.
11. Create a new AIGuard marker.
12. Select your marker, position it where you like and hit (F3) to modify the marker.
13. If you want to override the default respawn value - create a dynamic variable called respawn and set it's value to true or false.
14. Update your item by clicking 'APPLY'- very important and easy to miss step.
15. Save your mission and reload it.
A bot called Guard1 should appear at the spot of your marker.
If you come within range of the guard he should shoot at you and try to hunt you down.
If you get away, or when you die, he should return to his post.
I hope the resource helps other people get up and running with some AI code in their game.
And again, I'd like to thank the other members of this website whose code has been used in several places in the scripting to make this all work.
Mark H.
P.S. I've also included my AIPatrol class files with this - to install it follow the same instructions as for AIGuard, just substitute AIPatrol where AIGuard appears in the instructions. They can both be run at the same times with no problems.
P.S.S. 11/28/04 - I modified the AIPatrol.cs file to correct for a couple of typos.
P.S.S.S 12/3/04 - Added ammo and health seeking capabilities and fixed some errors. (Read posts below - or file in .zip for full details.)
This is my second attempt at making an AI controlled character. The first was an
AIPlayer that would follow paths. This character is a guard unit. The guard will
wait at it's post (spawn point) until it sees a target. It will then attack that
target while trying to close with it.
If the target is lost the bot will wait at the last place it saw the character and
look around for a little bit, and then it will try to return to it's post.
There is a chance the bot will get stuck trying to return, but there is a simple
routine that has the bot try to move in random directions to try and clear itself
of any obstacles between it and it's post. It's not perfect.
The thinking routine is a simple state machine - which can be expanded on to give the bot more responses and actions.
As with my first ai character, I am using a simple system that allows the designer to drop
markers in the game map that will mark where the bots will start out. When the mission is loaded, the markers are detected and bots are spawned at the marker locations. The markers are then hidden from view. (The markers can be left visible to help in map editing.)
The markers for the guards can be given a dynamic variable called respawn. (Assigned to the marker during map editing.) 'Respawn' will determine whether a bot respawns or not upon death.
The bots have an attention setting. How often they scan is determined by their attention level. The bots get more sluggish (freeing up processor time) when targets are too far away. Conversely, the bot becomes incrementally more attentive as targets come within range, and further aware as targets come into sight.
When a target is found in range and in sight the bot will shoot at the target. The firing sequence is a step of scheduled calls that call for a firing cycle, a trigger down cycle, and a firing delay to control bot rate of fire.
When a bot is attacked it will attempt to sideatep and it's field of vision is temporarily increased to a 360deg field of vision - to emulate looking around to see what happened. The bot's attention level is also set to make it think at it's fastest rate when attacked.
To use the AIGuard...the following changes need to be made.
1. Back up your original game.cs, player.cs, and your current build of Torque. To install AIGuard will require a recompile, since I have created a new class cloned by copying AIPlayer.cc and AIPlayer.h and renaming all references to AIPlayer to AIGuard.
(I did this because I wanted to be able to run both my AIPatroller and AIGuards in the same maps and did not want to have any confusion between them.)
2. Add the files AIGuard.cc and AIGuard.h to your Torque project. (In my instance I saved them to my c:\Torque\engine\game directory and then added them into my project.)
3. Recompile your project and copy your new executable to the appropriate directory for your app.
4. Copy the file AIGuard.cs into your server/scripts directory.
5. Modify game.cs to add the line
exec("./aiGuard.cs"); to the function onServerCreated().
6. Also in game.cs: The section for function StartGame needs to modified the following ways:
Below the lines that read:
// Start the AIManager
new ScriptObject(AIManager) {};
MissionCleanup.add(AIManager);
AIManager.think();add this:
AIGuard::LoadEntities();
(If you followed my previous resource you may not have any reference to AImanager. Don't fret... just look for the place in game.cs where you have
AIPlayer::LoadEntities
and put in
AIGuard::LoadEntities();
right underneath it.
7. In player.cs in the code for Armor::Damage modify the lines
// Deal with client callbacks here because we don't have this
// information in the onDamage or onDisable methods
%client = %obj.client;
%sourceClient = %sourceObject ? %sourceObject.client : 0;
if (%obj.getState() $= "Dead")
%client.onDeath(%sourceObject, %sourceClient, %damageType, %location);to read:
// Deal with client callbacks here because we don't have this
// information in the onDamage or onDisable methods
%client = %obj.client;
%sourceClient = %sourceObject ? %sourceObject.client : 0; if (%obj.isbot == true)
{
%obj.attentionlevel=1;
%obj.enhancefov(%obj);
}
if (%obj.getState() $= "Dead")
{
if (%obj.isbot == true)
{
if (%obj.respawn == true)
{
%obj.delaybeforerespawn(%obj.botname, %obj.markerpos, %obj.marker);
%this.player=0;
}
}
else
{
%client.onDeath(%sourceObject, %sourceClient, %damageType, %location);
}
}*** If you followed my previous resource there should be no need to change this code.
8. Load your map - Stronghold as an example.
9. Go into the map editor. (F11) Then go into the Editor Creator (F4)
10. Under Shapes there should be a drop down called AIMarker, under that a new item called AIGuard.
11. Create a new AIGuard marker.
12. Select your marker, position it where you like and hit (F3) to modify the marker.
13. If you want to override the default respawn value - create a dynamic variable called respawn and set it's value to true or false.
14. Update your item by clicking 'APPLY'- very important and easy to miss step.
15. Save your mission and reload it.
A bot called Guard1 should appear at the spot of your marker.
If you come within range of the guard he should shoot at you and try to hunt you down.
If you get away, or when you die, he should return to his post.
I hope the resource helps other people get up and running with some AI code in their game.
And again, I'd like to thank the other members of this website whose code has been used in several places in the scripting to make this all work.
Mark H.
P.S. I've also included my AIPatrol class files with this - to install it follow the same instructions as for AIGuard, just substitute AIPatrol where AIGuard appears in the instructions. They can both be run at the same times with no problems.
P.S.S. 11/28/04 - I modified the AIPatrol.cs file to correct for a couple of typos.
P.S.S.S 12/3/04 - Added ammo and health seeking capabilities and fixed some errors. (Read posts below - or file in .zip for full details.)
#242
You only need to add the global "$AI_GUARD_MINIMUM_CLOSING_DISTANCE = 20;"
and your changes in the the "think" function in the "attack" case. The other cases should be left as is in relation to what you are trying to do. GJ figuring it out though.
Trey
05/31/2007 (5:56 pm)
@Louis Dufresne You only need to add the global "$AI_GUARD_MINIMUM_CLOSING_DISTANCE = 20;"
and your changes in the the "think" function in the "attack" case. The other cases should be left as is in relation to what you are trying to do. GJ figuring it out though.
Trey
#243
If there is anyone out there that has not implemented this and at least toyed around with it, I HIGHLY recommend that you do so!
'Will
06/06/2007 (8:23 pm)
This resource is really an excellent one.If there is anyone out there that has not implemented this and at least toyed around with it, I HIGHLY recommend that you do so!
'Will
#244
It is currently all done via scripting.
The resource works off of (but doesn't require), the AI Guard file.
Thanks,
Will
06/06/2007 (9:51 pm)
If there is anyone interested I have recently posted an Experience Point and Stat system as a resource. It is currently all done via scripting.
The resource works off of (but doesn't require), the AI Guard file.
Thanks,
Will
#245
06/07/2007 (5:50 am)
Yes Will, please do post a link to the resource!
#246
www.garagegames.com/index.php?sec=mg&mod=resource&page=view&qid=13020
06/13/2007 (10:13 am)
Here it is:www.garagegames.com/index.php?sec=mg&mod=resource&page=view&qid=13020
#247
07/30/2007 (7:19 pm)
The bots, for me, do not go after more ammo nor do they seek health when needed. If they run out of ammo they just run after me and stop as if they are dry firing. Any clues?
#248
I have both guard and patrol in, and have the melee in, but I am getting problems and my console log is filling up with the following error
starter.fps/server/scripts/inventory.cs (140): Unable to find object: 'SwordAmmo' attempting to call function 'getName'
I know this is coming from Aiguard, and I have set it so that its
$AI_GUARD_WEAPON = "Sword"; //Which weapon do you want the guard to use
$AI_GUARD_ENDLESS_AMMO = false; //When set to true the guard will replenish its ammo perpetually
$AI_GUARD_WEAPON_USES_AMMO = false; //Set this to false for energy weapons that do not use ammo
I have gone through the code, and theres alot of if statements dealing with ammo.
Its not that its a huge matter, but I like to see a clean console log, and this is filling up for everytime that the guard attacks, as long as I can get them to apply damage to.
Any help would be great. Thanks again in advance
08/22/2007 (12:14 am)
I was wondering if anyone was able to implement this with the melee resource too, instead of crossbows, the guards and patrols are using melee weapons, if it applies the damage and what not.I have both guard and patrol in, and have the melee in, but I am getting problems and my console log is filling up with the following error
starter.fps/server/scripts/inventory.cs (140): Unable to find object: 'SwordAmmo' attempting to call function 'getName'
I know this is coming from Aiguard, and I have set it so that its
$AI_GUARD_WEAPON = "Sword"; //Which weapon do you want the guard to use
$AI_GUARD_ENDLESS_AMMO = false; //When set to true the guard will replenish its ammo perpetually
$AI_GUARD_WEAPON_USES_AMMO = false; //Set this to false for energy weapons that do not use ammo
I have gone through the code, and theres alot of if statements dealing with ammo.
Its not that its a huge matter, but I like to see a clean console log, and this is filling up for everytime that the guard attacks, as long as I can get them to apply damage to.
Any help would be great. Thanks again in advance
#249
Thanks
09/23/2007 (10:33 pm)
I followed all of the directions but for some reason I can't find the aiGaurd Marker under shapes. I looked through the codes a few times and I couldn't find any errors. I am using the 1.4.2. version of TGE. Do you think that the version is messing up the aiGaurd? Please respond if you have any suggestions.Thanks
#250
09/23/2007 (10:47 pm)
Great script, had a little trouble getting the enemy to damage player at first but realized it was a problem with the copied player2.cs that I made in order to use a model other than the player model. Fixed that and works great. This script gets my project rolling! Thanks!
#251
Thanks
09/26/2007 (10:35 pm)
Well I reinstalled TGE and tried the AIGuard again...and i finally found the marker. But it doesn't have a weapon, it won't move, and i can walk right through him. Any suggestions???Thanks
#252
09/27/2007 (7:21 am)
Hey how would I add an alert sound that plays when the AiGuard sees the player?
#253
You have to do this part. Or else you will never get this resource to work.
But if you have done the above...
The markers look like guards but are not guards. They are placeholders to show where in the game your guards would be, if they were being loaded. In the AI_Guard script there is a variable at the top part of the code that tells whether you want the markers to stay visible or go invisible after the guards are loaded.
One thing you can do is search through your console for a line that says...
Loading Guard entities...
If it's not there, then the script hasn't been told to load in game.cs. If it is there and you start getting the unknown object errors it's a compilation issue more than likely.
The fact that you are seeing the markers and no guards tells me that there is probably a problem when calling the functions to load the guards. The best I can offer - since I havent really looked at this code in a long time - is that you go back through and follow the instructions one more time, and check through your console for errors in regards to calling the AI_Guard class.
Jesse P - In regards to the sound playing... I don't have a clear answer for you. It could be done using a Audioemitter whose position is set the the guards position at the time that you start playing the sound. My old tutorial on doors has example of how to play a sound and set it to the location you want.
The link to that resource is:
http://www.garagegames.com/index.php?sec=mg&mod=resource&page=view&qid=6780
Just look through for the parts on AudioEmitters and you should see that it shouldn't take much to get you going.
You would just need to put the commands to play the sound in the 'Think' part of the bot's logic.
Actually you'd be better off writing a short function that would check everytime the state was set to 'Attacking' to see if the previous state had been something else. Otherwise the sound would repeat every time the 'Think' cycle processed and the state was set to 'Attack' again.
I'm not up on my Torque script much these days or I'd give you a complete solution, but I hope I've at least put you on a path toward the right direction.
09/27/2007 (9:36 am)
In regards to the marker problem. Have you read through the instructions and added the new 'C' class files to the engine and recompiled it? If you have, have you moved the new compiled version of the engine from the build directory to the current game directory.You have to do this part. Or else you will never get this resource to work.
But if you have done the above...
The markers look like guards but are not guards. They are placeholders to show where in the game your guards would be, if they were being loaded. In the AI_Guard script there is a variable at the top part of the code that tells whether you want the markers to stay visible or go invisible after the guards are loaded.
One thing you can do is search through your console for a line that says...
Loading Guard entities...
If it's not there, then the script hasn't been told to load in game.cs. If it is there and you start getting the unknown object errors it's a compilation issue more than likely.
The fact that you are seeing the markers and no guards tells me that there is probably a problem when calling the functions to load the guards. The best I can offer - since I havent really looked at this code in a long time - is that you go back through and follow the instructions one more time, and check through your console for errors in regards to calling the AI_Guard class.
Jesse P - In regards to the sound playing... I don't have a clear answer for you. It could be done using a Audioemitter whose position is set the the guards position at the time that you start playing the sound. My old tutorial on doors has example of how to play a sound and set it to the location you want.
The link to that resource is:
http://www.garagegames.com/index.php?sec=mg&mod=resource&page=view&qid=6780
Just look through for the parts on AudioEmitters and you should see that it shouldn't take much to get you going.
You would just need to put the commands to play the sound in the 'Think' part of the bot's logic.
Actually you'd be better off writing a short function that would check everytime the state was set to 'Attacking' to see if the previous state had been something else. Otherwise the sound would repeat every time the 'Think' cycle processed and the state was set to 'Attack' again.
I'm not up on my Torque script much these days or I'd give you a complete solution, but I hope I've at least put you on a path toward the right direction.
#254
-JP
09/27/2007 (11:55 am)
Thanks Mark, that'll get me rolling. And great AI script, this really has helped me start my project-JP
#255
09/29/2007 (11:39 pm)
What exactly is recompiling?
#256
With the game engine you also get the source code files that make the game engine. These files need to be converted from the programming language into the actual machine code that the computer understands. That process is called compiling.
Because this resource creates a new 'class' for the game engine to refer to... similar to an audioemitter or other 'objects' that the game uses, these files need to be re-compiled with the other original source files to make it part of the actual game program itself.
Adding just the script files from this resource will not let this work.
If you have no idea what compiling is, you probably don't have a program that will 'compile' the original source code. Maybe you do. There are several different compilers available such as Microsoft Studio and such. What you use is a matter of your own preference and budget.
If you look through the forums you will probably find some other information on how to compile and which compilers are available and all. It's a large topic to address but the Torque documentation has information on how to do it as well.
But if you don't have a compiler but still want to play some with the AI stuff, there is a previous version to this resource that modifes the path following Kork to make him shoot at you. That one is all script based and can be found here:
http://www.garagegames.com/index.php?sec=mg&mod=resource&page=view&qid=6742
09/30/2007 (1:32 pm)
Jamal,With the game engine you also get the source code files that make the game engine. These files need to be converted from the programming language into the actual machine code that the computer understands. That process is called compiling.
Because this resource creates a new 'class' for the game engine to refer to... similar to an audioemitter or other 'objects' that the game uses, these files need to be re-compiled with the other original source files to make it part of the actual game program itself.
Adding just the script files from this resource will not let this work.
If you have no idea what compiling is, you probably don't have a program that will 'compile' the original source code. Maybe you do. There are several different compilers available such as Microsoft Studio and such. What you use is a matter of your own preference and budget.
If you look through the forums you will probably find some other information on how to compile and which compilers are available and all. It's a large topic to address but the Torque documentation has information on how to do it as well.
But if you don't have a compiler but still want to play some with the AI stuff, there is a previous version to this resource that modifes the path following Kork to make him shoot at you. That one is all script based and can be found here:
http://www.garagegames.com/index.php?sec=mg&mod=resource&page=view&qid=6742
#257
Thanks.
09/30/2007 (2:32 pm)
I just tried the resource and it worked! I have one last question...Can't someone recompile the code and then send it to me??? Thanks.
#258
Update: I solved part of what I needed from a post I found on this page :) and now it no longer displays the status, but it says Guard1 over its head. How do I remove that? Thanks
Update #2: GOT IT! I just commented out wherever it said setshapename in aiguard.cs
10/07/2007 (3:38 pm)
Hey how do I remove the text that hovers above the guard when in game. The text that says the numbers and attacking, returning, etc.Update: I solved part of what I needed from a post I found on this page :) and now it no longer displays the status, but it says Guard1 over its head. How do I remove that? Thanks
Update #2: GOT IT! I just commented out wherever it said setshapename in aiguard.cs
#259
10/07/2007 (7:05 pm)
Glad to see you found the answer. :-)
#260
Does anyone have the names of the correct files to add the includes?
Also, I've noticed that the marker(which does show up) is not holding any weapon. I have looked and have found no reference in AIGuard.cs to what shape file the bot is supposed to hold. I tried changing the weapon name to Crossbow and Weapon. to have the default Orc weapon, but that did not work.
Anyone have a fix to that one as well?
Thanks in advance for any help.
10/31/2007 (8:24 am)
Ok, I've tried to get this working and I'm having a few problems. I'm having the same problems Wayne Eversole had with the console log. I have checked the C++ files, but I found about 5 places that contain 'aiplayer.h' and if I include aiGuard in them all I get errors.Does anyone have the names of the correct files to add the includes?
Also, I've noticed that the marker(which does show up) is not holding any weapon. I have looked and have found no reference in AIGuard.cs to what shape file the bot is supposed to hold. I tried changing the weapon name to Crossbow and Weapon. to have the default Orc weapon, but that did not work.
Anyone have a fix to that one as well?
Thanks in advance for any help.

Torque 3D Owner mb