Daily Archives: May 7, 2014

Leave a reply

Tutorial – Game State Machine – How/Why You Should Use Them

Like a lot of people, I first started programming because I liked video games. Of course, back when I was younger we made DOS games in QBasic that were nothing more than simple multiple choice text adventures. The code back then was a lot like this:

Print "A wild GOBLIN appears"
Print "(A)ttack. (R)un"
Input a$
if a$ = "a" GOTO 6
if a$ = "r" GOTO 7
Print "You ATTACK the GOBLIN"
Print "You RUN from the GOBLIN"

That may not be exactly how the code was written, but it’s been 20 years since I wrote in QBasic.

Lets examine this code for a moment:
Line 1 Prints a string to the screen
Line 2 Prints a string to the screen
Line 3 Records user input
Line 4 and 5 tell the application to do something based on the input supplied
Line 6 and 7 are the result of the input supplied

Games these days are not much different from this exact scheme. You give the user a situation and a means to work with that situation and then display the result of the player’s choice. It doesn’t matter if it’s a World of Warcraft boss or a wild GOBLIN appearing out of no-where. Now you can imagine writing something as complex as a WoW boss fight using QBasic would be less fun than swallowing glass, but the idea is the same.


if(bossHealth >= 75.0f) {
    bossState = State.PhaseOne;
  } else if(bossHealth < 75.0f && bossHealth > 50.0f) {
    bossState = State.PhaseTwo;
  } else if(bossHealth < 50.0f && bossHealth > 0.0f) {
    bossState = State.PhaseThree;

  if(bossState == State.PhaseOne) {
    // Hurl a fireball

  if(bossState == State.PhaseTwo) {
    // AOE room with lava

  if(bossState == State.PhaseOne) {
    // Hurl a fireball
    // AOE room with lava
    // Immune to taunt

As you can see a boss fight can be made up of several different states, and the game can change depending on which state the boss is in. I used a very simple concept here just to explain what exactly a game state machine can do.

Lets take a look at a real example of a game state system. We will be using Unity3D and C# for this example but the idea should be portable enough to use whatever you are familiar with.