An overview of Finite State Machines (FSM) and how you can use them in your games for everything from character movement to controlling game states.
- [Instructor] To control for our players movements, we're going to use a well known programming pattern called the finite state machine. Finite state machine is set up using a switch statement. We transition between states based on inputs or events. Our state machine will only execute code that is associated with the given state when we're in that state, and it keeps our code clean and manageable by avoiding nested if statements which can quickly get out of control. This is what the finite state machine for our game will look like. Each one of the circles represents a state and will be a case in our switch statement.
The arrows in between the circles are state transitions, and they represent either player inputs, or events that happen in the game. Let's take a look at how it will work. Our player will initialize to the idle state, and the only thing we're allowed to do in that state is press the space bar so that we can start running. Once we're in the running state, we have two things that we can do. Either press the space bar to jump, and then once we're in the jump state, we'll exit the jump state when the ground collision event happens which brings us back to running, where we can also press the down arrow to duck, and once in the duck state, we'll stay there until we release the down arrow to start running again or press the space bar to jump.
The only remaining state is our dead state, which we'll enter when we collide with an obstacle. Once this has happened, the level will restart, and we'll go back to the idle state. This programming pattern is a great architecture to learn. I use it all the time for player controls, game controllers, and the like. And since this architecture separates our code out into states, we can focus on one state at a time.
- Setting up basic game components
- Creating the player object
- Using Finite State Machines
- Making the player duck
- Creating physics fixtures in code
- Creating physics obstacles
- Box2D liquid physics
- Creating particles that behave like water
- Creating a floating blocks obstacle
- Creating a swinging chain obstacle and a rope bridge
- Adding the finishing touches