Pagina's

Thursday 9 January 2020

Sequencing the states

Good afternoon. Yes you heard that right. It's even almost evening and I'm in the bus back home from work. I was just thinking about the state machine that I'm running in Holocene and there's a problem.

The problem is not unfixable by any means, but it'll make my job a lot more difficult because I am bound to create a gigantic AI class if I continue what I'm doing now.  Shop what am I doing really? Well, I'm using a state class that has actions defined for entering and exiting the state and for executing whatever the state needs for every frame. All these methods are written in the CharacterAI class.

The idea is that once something is happening, like the character finds out he's hungry, the decision class will look if there's apples to eat and if there are, trigger Moving state with an apple as target. That's all fine and that works, but...

Walking to an apple is not really the same as eating it and moving to any target does not satisfy hunger feelings, so I have to make it more complex. Once the character arrives at the apple, he'll have to interact with it.  Pick it up, maybe prepare it and consume it.  That means we need more information on what to do next. That is going to clog the system quickly.

Now here's my idea: I'm going to use the Unity animator controller and add behaviour scripts to any of the states, keeping them very modular. Moving does just the walking until it's at the destination, picking up just picks things up, eating only destroys the object and sees if that does any good to the character. All these states can me called by a simple trigger that takes a string or an int.

Back in the AI script, all I have to keep track of its a stack of triggers. The states will let the AI know they're finished and the AI will know what to do next. In the eating example, the character will run a "hunger" method and that'll populate a stack with the state for finding it there it's food nearby, plotting the road, going there, picking the food up, seeing if it needs preparing, doing that, eating the food and going back to seeing what to do next.

I'm sure this is easier said than done, but I think this is what I'm going to do.  This way I keep the code separate and unrelated and that often means less bugs and easier to manage.

2 comments:

  1. Sounds nice but also a bit complicated and it probably is close to behavor trees. I use behavor tree heavily for all kind of AI in my game and it keeps it simple and the task are really smallish code wise as well very reusable. It’s different thinking than state machines but IMO more powerful. I even used it for gun behavor like eject shells, reloading, delays between the bullets fired and so on :D

    ReplyDelete
    Replies
    1. Interesting. I don't know much about these AI patterns. I'll have a look. Thank you for the feedback!

      Delete