Game Development Community

dev|Pro Game Development Curriculum

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

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.)
#181
08/12/2006 (1:18 pm)
OMG, my bad sorry.
I have 2 example folders in my engine, one for backup and other im working out of. I forgot that the TSE.exe file got updated in example folder and not MyGame folder lol.
Sorry for the big head ake.
Great resorce by the way.
Thanks
#182
08/12/2006 (2:04 pm)
I hope that means you got it to work for you.
#183
08/15/2006 (2:28 am)
Works Great Thanks.
Just a newbie mistake of forgeting to copy the tse.exe over to my game folder im working out of lol.
#184
08/16/2006 (3:09 pm)
I do get a spam msg in the console that reads
aiGuard.cs (436): Unable to find object: '' attempting to call function 'getPosition'
any ideas?
thanks
#185
08/22/2006 (6:10 pm)
my guard dude just twitches.

and turns around. it only reads holding, returning, nothing else

im standing right besides him and he isnt chasing me. any idea???
#186
08/24/2006 (9:01 am)
hi, again... the gurad doesnt seem to want to move at all. when i add 10, occasionally one jsut randomly shoots, but non chase me and or attack, theres just this random one that shoots occasionally and for no reason either.

any idea how to make them chase me?
#187
08/28/2006 (12:30 pm)
Tom,

Have you followed the instructions to the letter? I'm guessing you probably missed a file or modification. Also, try rebuilding the entire solution (Or make clean, on linux).


Additionally, try clearing DSOs and preferences.

Hope this helps.
#188
08/30/2006 (8:22 am)
First of all thanks Mark, great resource, looking forward to understand it now...

I got an issue with the framerate while executing AIGuards. I got 3 of them in the mission and the fps is between 35-40, wich is great. Now as soon as one of them gets berserk and starts charging my player, fps falls to 5-6 or so.

My computer is quite decent but my graphic card is an old Geforce 4. Actually I kinda see where the problem is coming from so I'm not asking why, just asking if someone else is facing this ? How many instances of AIGuard can you run at the same time guys before it is barely playable ?
#189
09/05/2006 (8:59 pm)
I'm having a similar issue with the bot not responding. Actually, I have done some troubleshooting and discovered that the CheckLOS function isn't working correctly, though I'm not exactly sure why as the code looks good. The only thing I added was the "$TypeMasks::AtlasObjectType" since I'm using TSE, though the problem exists without the TypeMask in there too. Check out this code from the CheckLOS function:

%eyeTrans = %obj.getEyeTransform();
%eyeEnd = %tgt.player.getEyeTransform();
%searchResult = containerRayCast(%eyeTrans, %eyeEnd, $TypeMasks::InteriorObjectType |
$TypeMasks::StaticShapeObjectType | $TypeMasks::StaticObjectType | $TypeMasks::AtlasObjectType |
$TypeMasks::TerrainObjectType | $TypeMasks::PlayerObjectType, %obj);
%foundObject = getword(%searchResult,0);
echo(%foundObject);

%foundObject returns a zero even with me standing in front of the bot. Now, if I start jumping around like a maniac occasionally the bot will see me... then lose me again. It's like he's looking through a door peep-hole and only seeing me in certain spots. I've also tried changing getEyeTransform to getEyePoint with the same results. Any ideas? :)
#190
09/06/2006 (7:02 am)
hey man
this is a very good resource and is pretty much helpful

but i am stuck in middle of something while implementing the aiguard and aipatrol
i had followed the steps of implementation as mentioned above
but in the last 2 steps i have a problem which i couldn't understand or rectify on my own
the problem is that when i put the aiguardmarker into it and then when i hit apply i get an error message saying

(0): Unknown command apply.
Object inspector(1443) inspector -> GuiInspector -> GuiStackControl -> GuiCont
rol -> SimGroup -> SimSet -> SimObject

does anyone else has ever encountered this sort of a problem ?
can anyone help me out of it
please if someone could just help me out of this trouble and tell me anything about how to fix this thing
i would be very thankful to him

thanking you
#191
10/03/2006 (2:35 pm)
I have the AIguard and AIpatrol in my game, they both work great. Now I am simply trying to change their models so they dont look exactly like the player. I went through AIguard first and changed his shapefile to another dts and he either still comes in as the player model, or is he is the other model he moves and shoots but has no animation..like a doll floating over land

the custom model I have already works in Torque, so I have tested all that out, I just cannot figure out what else I am missing here, any suggestions?

EDIT:
sorry, got it all working
had to look bad to an old project we did with four selectable players and how we did it then, and it worked...thanks anyways
#192
10/07/2006 (1:39 am)
Isnt this the same thing what it teaches in advanced programming all in one?
#193
10/07/2006 (9:03 am)
In essence yes, Mr. Finney's book does cover a similar unit as this one.

The major difference, and probably the reason this forum topic has lasted this long is that his book was just recently published, whereas this resource was posted nearly two years ago.

And in all honesty there are several similarities in the code for both of them, which doesn't surprise me since I took some of the ideas for the code from his original book and added and expanded them in my own way to create this unit.

His code is a little different than my own and in truth is probably better in some places. I'm sure he spent a lot more time refining his, plus he's more accomplished in Torque than I'll claim to be.

Personally I don't want to even begin to get into a debate or comparison over his code versus mine. He's a professional programmer/bookwriter and I've learned most of what I know about Torque from his books. I'm just a guy who threw this code together as both a learning tool for my own sake and as a potential help to others at a time when there was very little AI code for Torque in the forums.

My only intention was to offer this up as a means to help people and I hope that it has. If someone has come along with something better, well I'm glad and hope it works well for others. To me that's the whole purpose of these forums and the small game making community.

And I mean no disrespect to Mr. Finney in what I say next, but I'm sure he looked at this code in the course of setting up his own code. And in looking at it I'm sure he saw where I had taken things learned from him. And he may have taken a few ideas from mine.

I'm not implying that he took my code. First of all it was based on his work anyway, so how could I begin to get offended. Secondly it was posted in a public forum for all to see and use.

So even if he did look at this code (And I'm not saying he did.) and did clean it up, well good. That goes back to the whole community thing. I'm just glad that there's a decent resource for other people to use.

Now before you think that I'm placing myself on a pedestal and am having delusions of self importance take a look at the section on doors in Mr. Finney's book, and then go back and read the acknowledgements in the front of the book. And after that you'll understand why I can say the things that I'm saying, and why I have nothing but respect for Mr. Finney.
#194
10/07/2006 (5:14 pm)
how would i make the bot play a death animation and then switch to the debris file???? i've been trying to get this to work for a while without success. i would greatly appreciate any help, plus i think it would be useful to know how one would go about this with these bots, because its sort of boring that they just lie there.

btw: amazing resource, thank you so much for offering it to the community, you rule!
#195
10/08/2006 (6:38 pm)
Mark,
I just implemented your code - (v 1.4) - works great.


Awesome resource -

I'm using JetPacks for my player - and I'm going to see if I can integrate this for the guards as well.

Thanks!
Sam
#196
10/11/2006 (3:03 am)
Note- I had the same issue with the bots not seeing my player (custom) and found out that if i moved the players center point to chest level, the bots find me alot easier. This has to do with the LOS being drawn to the bounding boxes centerpoint by default if the proper object/node/LOS is not present.
Origionally my objects point was between his legs, as that was easies, but then i moved it to mid chest.

I still have issues with the bots losing track of me. If i shoot the ground beside the bot, if the splash damage hits the bot, he looses me, even if im in front of him.
If i shoot past him he re-aquires me and attacks, or if he returns to his start box he will then find me too.
#197
10/19/2006 (4:57 pm)
nvm, the option to actually load aiguards was defaulted to false
#198
10/28/2006 (6:58 pm)
Just put the AiGuard and AiPatrol into my TGA 1.5 build worked perfectly.
#199
11/17/2006 (5:04 am)
I have tried it in Torque 1.5 and it did not work. I tried many times and it will not load it just crashes. But it works in TLK and in Torque 1.4, like a charm.

I saw Levi got it to work. Did you do any altering to it.
#200
11/17/2006 (9:55 am)
No don't think I chanted a thing. What errors are you getting? Rre you having troubles compileing the engine? If you can get it to compile what are the errors in the console?