Introduction to State Machines

We often write code to react to things happening within the game environment based on the expectations of us, as well as our players. For instance, if we are creating a 2D side-scrolling platformer game, when the player presses one of the arrow keys, we're expecting the player's character to move and, whenever we press the spacebar, we expect the sprite to jump into the air. Or perhaps in a 3D game, when our player sees a panel with a large button, they expect to be able to press it.

Tons of things in our ordinary lives act this way as well, reactive to certain stimuli. For instance, when you use your television remote, you expect certain things to happen, or even when swiping or tapping on your mobile phone. Based on the stimuli provided, the state of our object may change. We call something that can be in one of multiple states at a time a State Machine.

Almost every program you write can be considered a State Machine of some sort. The second that you add in an if statement to your project, you have developed code that can be in at least one of those states. That being said, you don't want to have a bunch of switch and/or if statements inside of your code as it can quickly get out of hand and make it difficult to understand exactly what it is that your code is doing.

As programmers, we often want to take our problems and break them down over and over again until they're in their simplest form, so let's see a possible way to do that. In game development, you'll hear references to an FSM which stands for Finite State Machine. Finite means that there are only a certain number of states and that they are all clearly defined for what they can do and how they will change between states.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.197.95