Sunday, August 2, 2009

Enemy AI

I notice that a lot of people seem to have trouble coming up with some good AI for their games. I have trouble with this as well, so I thought I would detail the process I performed when I created an enemy AI for my platform-shooter.
First, I wrote down the basic things I wanted the AI to do. That came up with something like this:

-Patrol an area when idle
-Be able to 'spot' the player, and give chase
-Be able to try and shoot the player is in range
-Be able to jump over and onto obstacles

Listing it out like this provides you with some guidelines, which is much better than simply thrashing out some code without a clear idea of what you want.

The next step is to write out the basic idea of your code. This might be pseudo-code, or just normal code. A simplified version of my code might look like this:

//if we are in idle mode
if state=0 {
//look for the player. if we find him, transition into alert mode
//patrol an area x pixels wide
//if an obstacle is encountered, jump
}
//if we have spotted the player and gone into alert mode
else if state=1 {
//if the player is out of range, go back to idle mode
//go towards the player
//try and shoot the player
//if an obstacle is encountered, jump
}

As you can see, this is very simple, but gives you a good outline of what you are trying to accomplish. From here, you can write your basic code. Chances are, it won't work perfectly the first time you try it out, which is where iteration comes into play. Just test out the AI, and when it does something unrealistic or stupid (like walking into walls, or shooting in the wrong direction), figure out what it should be doing (jumping over the wall, shooting the other way), and fix that in the code.

With enough iteration, you should get a good code that works about how you wanted. You might find it doesn't exactly match up with your original guidelines, but often times it is even better than what you predicted.

Fun fact: At one point in my AI development, that enemies could actually jump onto each other, and would stack themselves up to get at me. It was pretty entertaining to watch.

2 comments:

  1. Thats pretty much my process for AI too. I think I wrote a post just like this a little while ago.

    I had that problem too... I thought I could make the enemies not overlap by just making their parent the block object! XP

    ReplyDelete
  2. Really? I'll have to check that post out.

    Haha. That's exactly what I did.

    ReplyDelete