Hierarchical State Machine

One of the projects I worked on while learning Game Design was to develop a state machine in Unity. A state machine is a basic form of AI in video games where the NPC's switch between different states depending on stimuli from the environment. I prefer to use behavior trees because they have more use cases, but the assignment required that I use a State Machine, so I decided to create a hierarchical one. The game itself is quite simple. It is similar to games like Agar.io and the cell stage of Spore, where you play as a cell that eats other cells that are smaller than you, and then grow bigger.

Gameplay Video

You can see the predator (red) and prey (green) interacting as they go through their state machines.

State Base Class

Every state has a few different methods for what happens when they start, are updated, and exited. They are also made the child of a State Machine object which tracks the current state and transitions between them.

Each state also knows if it has a parent state, or various substates, and how to transition between them.

State Examples

Different states can easily be created by inheriting from the State class, and overriding the different methods as needed. For Default and Passive, it triggers the transition in the parent state machine when that state starts.

For the eat food state, it only cares if the state machine is already in the state, triggered from another states transition when their is food in range. If it is updating, it waits a set amount of time for how long it should be eating for, then transitions to the done eating state. It also sets its tracking target to null so that it can get a new target, either plant food or a prey entity.

Previous
Previous

Ricochet Noir

Next
Next

Persephone IX