Thursday, October 04, 2007

Generic XNA - A.I Finite State Machine

I have a great book Programming Game AI By Example by Mat Buckland. The first chapter was an eye opener for me as it is a Maths and Physics Primer which is just what I needed, I have not used either of those parts of my Brain since 1988 and they are a bit whithered :P

Anyway I digress. The next chapter is on Finite State Machines (FSM), I have a little experience of these having played with writing very simple CA's (Cellular Automata) way back when.

So I thought, "I have not seen any examples for A.I in XNA yet, wouldn't it be nice, using the examples in this book to come up with a FSM A.I for XNA" So that is what I have tried to do here in this post.

The basic model I put forward here IMHO is quite extensible, you have two base class's and an interface, the BaseAgent, BaseState and IBaseAgent. These objects are the framework of the FSM, to create a new Agent just inherit from the BaseAgent and create an agent interface to go with you new Agent class off the back of IBaseAgent and create your new states inheriting from the BaseState for each, then have your None Player Character or Bot (NPC) inherit from the new interface and write your AI logic for your NPC in the interface stubs.

In this example project I have just implemented the base states:


I guess these are the most basic items an NPC will need, you can always add other states like Seek and Chase or anything else you may need your NPC to do.

The NPC Patrols...

The NPC Fights!

The NPC Flees!

Again, this is a simple example, but I hope it gives you a base to work from and develop your own FSM's and as ever, if you think I am going about it wrong, leave a comment, it's the only way I can improve my examples.

AWSD - Translate Camera
Mouse - Rotate camera.

Move to the plane while it is patrolling in a circle, it will engage you and once it has lost enough hits will flee (don't worry, it loses hits just by being close to you)


  1. What is the difference between the runAway state and the Flee state in your AI system, they seem a bit redundant??

    DK Studios

  2. The runAway is the decision making part of the logic, it is where the agent decides when it should run or not, the Flee is the actual action of running away.

    Remember, this is just a framework, you can create what ever states and logic checks you want depending on your usage, you may not use any of the states I have created, you should create your own.

  3. Excuse, I have removed this message


Note: Only a member of this blog may post a comment.