Game Development Reference
1. Add the following code just below the preceding code you added:
2. Save the I]ej[>qc?]p_dan*]o file and test the project. The bugs will flee wildly from the cat if
it chases them, and bob around it complacently if it sits still.
All this adds up to very realistic bug behavior. In fact, the bugs almost seem to have some kind of intel-
ligence. That's why this kind of programming is called artificial intelligence , known as AI for short.
As you can see, there's nothing too special about his code, and there's certainly no magic formula
for writing it. I wrote this code with a vague idea of how I wanted the bugs to behave and spent an
hour or so playing around with a few different combinations of directives until I found something
I was happy with. To say that there are as many different ways the code could be written as there are
readers of the topic is an understatement. There are millions of ways this code could have been writ-
ten, and the example I present here is just one possibility I dreamed up on a snowy afternoon. When
you're programming objects that need some sort of awareness of the environment they inhabit, try
and break down their behavior into small steps. Solve one step and build from there. With just a few
lines of code and a few simple eb statements you can create something that appears alive and truly
intelligent. It's really not hard; try it!
Although it works well enough for me, there's one weakness in this code that you'll discover if you
play the game long enough. Because the bugs add the exact value of the cat's velocity to their own,
they always outrun the player. The only way you can catch one of the bugs is to trap it in a corner. To
make the game a little more realistic, you could add an extra bit of randomness, more or less, to the
value of the velocity obtained from the lh]uan object. But I'll leave that for you to figure out!
The next phase in the game is to actually catch the bugs. You need some kind of container to store
them in, such as a collection jar. In AS3.0, a collection jar for objects is known as an array .