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.)
#301
05/25/2008 (9:52 am)
Some one might have answered this before, but does that AIPatrol leave his patrol path when he spots someone within range to fight and chase them around? If not, then has someone posted a resource that makes this occur.
#302
06/20/2008 (10:06 am)
can anyone help? this would really help me move on... (4 posts up)
#303
07/02/2008 (7:04 pm)
ok so im wondering if i did the compiling with the .h and .cc files right. i downloaded visual c++ 2008 or something like that, and i clicked open project and selected torque demo. then i clicked add existing to project, and selected the .h and .cc file, and clicked recompile. is this right? i think i have everything else in this resource right, but when i try to start my game, the guards dont spawn. I found a part of my debug output that looks like this...

Loading Guard Entities...
starter.fps/server/scripts/aiguard.cs (350): Unable to instantiate non-conobject class AIGuard.
Set::add: Object "0" doesn't exist
starter.fps/server/scripts/aiguard.cs (366): Unable to find object '0' attempting to call function 'EquipBot'
starter.fps/server/scripts/aiguard.cs (368): Unable to find object '0' attempting to call function 'setShapeName'
starter.fps/server/scripts/aiguard.cs (370): Unable to find object '0' attempting to call function 'setTransform'
starter.fps/server/scripts/aiguard.cs (352): Unable to find object '0' attempting to call function 'schedule'

can anyone help guide me in getting my ai to spawn? thanks, and sorry this is an old post...
#304
07/02/2008 (11:10 pm)
I followed the tutorials to a tee, I was able to get the AIGuard marker in the world editor, it shows up as an orge with no crossbow. I save the game and restart mission, but the orge bot is gone, its not rendered. When i switch back to world editor, it shows that the AIguard Marker is still there but no orge anymore. Ive tried this a couple times on a clean backup folders, with no sucess. Can anyone help?
#305
07/03/2008 (12:05 am)
@John:

Here a tip: Perphas your torque demo build is not in example directory, so your are still using the old version. Check file time creation of your executable vs. executable in the example folder.

@Jason: check in in the aiguard.cs if you have: $AI_GUARD_ENABLED = true;
#306
07/05/2008 (12:35 pm)
i see what your saying i think, when i compile does it create in executable or something somewhere i need to copy to the example folder?
#307
07/10/2008 (9:19 pm)
This along with the AIPlayer resource is awesome. I was able to get this into TGEA 1.7.1 with some minor tweaking.

I do have one problem though. I have the Guard and Kork1 working. They spawn and attack just fine. The problem is I can't kill them. I unloaded a whole clip of crossbow bolts into them and they show no health but still keep on going. Were would be a good place to troubleshoot the problem?
#308
07/13/2008 (12:34 am)
First of all, sorry for my english. I'm spanish and I am a TGE user.

I'm trying to implement this resource on my game, but my players and bots are FlyingVehicles, not Players shapes.
I've created aa copy of the files aiGuard.cc and aiGuard.h for the Engine, replacing all sentences of aiGuard for aiFlyingGuard, and Player for FlyingVehicle, etc... and I've followed the same steps for aiGuard.cs.

My bots appears on the world but they don't move or shot...
Can anybody helps me about this?

Thanks!
#309
07/19/2008 (2:16 am)
I am having a problem, which seems to be common to other people.

When i go into the World Editor, the AI Marker apears, and i can place it. I then save exit and run my game again, and no AIGaurd spawns!

Originally, it came up in my console as: Guard entities disabled...

and so following Mark's responce to ebee t got that to dissappear, but now it comes up with:
Loading Guard entities...
starter.fps/server/scripts/aiGuard.cs (345): Unable to intantiate non-conobject class AIGuard
Set::add: Object "0" doesnt exist
starter.fps/server/scripts.aiGuard.cs (361): Unable to find object: '0' attempting to call function 'EquiBot'
starter.fps/server/scripts.aiGuard.cs (363): Unable to find object: '0' attempting to call function 'setShapeName'
starter.fps/server/scripts.aiGuard.cs (365): Unable to find object: '0' attempting to call function 'setTransform'
starter.fps/server/scripts.aiGuard.cs (367): Unable to find object: '0' attempting to call function 'schedule'
Hiding Guard markers...

I just can't get it working, and this is exactly the thing I need in my game

From Ross
#310
07/20/2008 (4:38 pm)
I haven't touched Torque in a while but as I recall that's the error it throws when you haven't added the .h and .cpp files to the project and recompiled it. Or you have recompiled it but you are running the old version of the program and need to find where the nex executable is stored.

The error message pops because you are trying to reference a class that doesn't exist in essence.
#311
07/22/2008 (12:45 am)
I have added the markers and then i save the mission. But when i load the mission i don't see any guards. I just see kork and all he does is run around. I have compiled and done all that stuff. The files are called AIguard so im not sure why it doesn't work. Does anyone know what i should do.
#312
07/25/2008 (6:03 pm)
"Or you have recompiled it but you are running the old version of the program and need to find where the nex executable is stored."

where do you find the new executable?
thanks
#313
07/25/2008 (6:59 pm)
I use Visual Studio and for me it's usually in a folder called BIN that exists in the folder structure where the game's source code is.

If you're using Visual Studio you can open the project, open the Solution Explorer and then right click the Solution name at the top of the list and open it's properties. Amongst all the other things on the left is a 'Configuration Properties'. Expand it and look at the item named 'General'. After you click on that it will list the 'Output' directory. But it won't show you the full path usually. But click on the output path like you want to change it and select browse from the list and it should show you the full tree to where it's sending the output file.

OR... If you need another way to cheat... open your project and make a small change to a part of the code like adding a couple extra blank lines somewhere or adding a new comment to make the compiler see the file as changed. Then just rebuild your file and then do a search on the hard drive for any *.exe files that have been created or modified in the last 24 hours. Not elegant but it should work for you.
#314
07/29/2008 (4:29 pm)
Hi Mark İ Use EveryThing But i Have Problem >>STEP 10. Under Shapes there should be a drop down called AIMarker, under that a new item called AIGuard.<< I See İt İn My Game Under Shapes then i click but do anything :S so this is not work i dont see anything on my screen i click ... i click...

>> (0): Unable to find function StaticShapeData::create Script Eror Message

HELP PLS
#315
08/04/2008 (8:10 pm)
thanks mark, i thought that would do it, but i just figured out that isnt the problem yet. i'm not compiling right... i get 42 errors and the build fails...

7>Build log was saved at "file://c:\Torque\TGE_1_5_2\engine\out.VC7.DEBUG\BuildLog.htm"
7>Torque Demo - 42 error(s), 0 warning(s)
========== Rebuild All: 2 succeeded, 1 failed, 4 skipped ==========

I've downloaded visual studio express 2008 and i set the output directory to the torque example folder. I've been looking at a lot of other threads concerning it, and i think im supposed to download a server thing and something else which i did a bit ago, but i dont know how to configure it with everything right. theres not many threads or tutorials for setting up 2008 so im wondering if it works fine and everything... or i just need to configure it right. mind shedding some light on my problem?

thanks a lot this has been annoying i bet.
#316
08/05/2008 (9:17 am)
Oguzcan... go back through and make sure that you copied the other folders for the marker and all to the right locations as in the instructions. That might be part of your problem.

John W.
I literally just installed Viz Studio 2008 last night. I will try to compile the code with it later today and I'll get back to you. One quick question. Which version of Torque are you using the Regular version or the Advanced version?

-Mark
#317
08/05/2008 (11:17 pm)
the regular, oh and my license i have on my other account... ill post with it right now
#318
08/05/2008 (11:17 pm)
k this is my account with the license
#319
08/06/2008 (12:15 pm)
John W. I took a fresh install of Viz Studio and a fresh install of Torque and tried compiling. I got the same results. So it has to do with just getting the basic compiler configuration to work. I'll look more into it later tonight. Seems like it might be a hairball just to get the program to compile regularly. Once I get it straight I'll let you know what steps it took to do it.

In the meantime you might look around on the site, I'd be surprised if someone hasn't already run across this and posted an answer.

-Mark
#320
08/06/2008 (3:22 pm)
How do i delete an AIGuard?