Unity: Using an FSM to control your GameObjects
Thanks to my good friend Maurizio, who’s been helping me removing the dust from my memory, today I’ll show you how to use a simple FSM to control your GameObjects 🙂
First, if you don’t know what an FSM is, please read this, and maybe this too.
Done? Good. Now take a look at this (use arrows and spacebar for jumping).
[unity src=”513″]
See? It’s just Mario walking on a small platform. He can jump (obviously, he’s Mario) and can fall from the borders.
There are tons of ways to implement this and one of them is using an FSM.
The Player and the bricks have only a BoxCollider2D, no Physics components. On the Player I have added a Script component that acts as a controller (code is on GitHub).
The idea is to let the controller initialize the FSM adding the needed States and define for each state the Transitions (basically destination State and condition ).
For this demo I have implemented three States: Default, Jumping and Falling. The transitions are simple:
- Default -> Jump: on “spacebar” pressed
- Default -> Falling: if no collision occurs on -Y
- Jump -> Falling: after 0.5 seconds
- Falling -> Default: if a collision occurs on -Y
The states themselves are pretty simple:
- Default: checks for input on the horizontal axis and moves the player
- Jump: adds an impulse to the Y of the player
- Falling: applies gravity to the player transform