State Machines and Programming

State Machines...

A state machine is more or less a system that takes either a single or multiple input(s) and does something depending on that input.

For example, the player's actions are taken into account and the Animation State Machine changes the animation that is currently played.
It's an efficient method of calling various methods to do things. Rather than having a massive logic loop, the current state of the thing in question can execute various code blocks.

The diagram above is Unity's Mechanim animator. It allows users to configure how the states move between each other.

Now that the states have been defined, the State Machine hasn't been made yet let alone the switching to the states, for the State Machine to function, something needs to switch the states based on player input. In this case, the PlayerController has that job...

//Move Right
if(Input.GetAxis("MovementP1") >= 0.5 f) {  
    thisTransform.Translate(0 f, 0 f, walkSpeed * Time.deltaTime);
    facingDirection = 1;

   if(!animationLock) playerState = PlayerState.Walk;
}
//Move Left
else if(Input.GetAxis("MovementP1") <= -0.5 f) {  
    thisTransform.Translate(0 f, 0 f, walkSpeed * Time.deltaTime);
    facingDirection = -1;

    if(!animationLock) playerState = PlayerState.Walk;
}

The above script handles the switching based on the input the player gives. Moving right or left switches the state to Walk. Now the State Machine can do it's work by executing something useful.

//Animation Switch System
switch(player.playerState) {  
    case Player.PlayerState.Idle:
        animComp.Play("Idle");
        break;

    case Player.PlayerState.Walk:
        animComp.Play("Walk");
        break;

    case Player.PlayerState.Run:
        animComp.Play("Run");
        break;

    case Player.PlayerState.Skill:
        animComp.Play("Skill");
        break;

    case Player.PlayerState.Attack:
        animComp.Play("Attack");
        break;
}



Below is what the end result looks like once the State Machine starts working with the player input.



So... Why should you use it?
Simply because how useful it is. It simplifies codes and promotes good programming conventions and code quality. It's also quite handy since you can use states for just about anything... player actions, animations (above) and artificial intelligence. In fact, why would you not use it for AI? It's perfect for it...

Tom Lynn

Read more posts by this author.

Australia http://rubbix.net