Game Development Reference
In-Depth Information
Pro Tip
Event listeners and delegates are extraordinarily powerful. There's no
longer any need to write massive amounts of state-check code for all
of your objects. Say you have a huge sequence occurring in your game,
such as a giant alien spaceship moving into attack position over a town.
Instead of having every single object in the scene constantly check the
state of the alien spaceship, just use event calls on the ship and event
listeners on the reactive objects to update their local states based on the
actions that occur. This saves time and headaches, giving you more time
to make that sequence even better rather than spending more time just
trying to make it work.
Phew! Now that the code is a bit lengthier, give it a good read and it's pretty clear
what is going on. What we have here is a decently powerful
State System
. With this,
we can manage how the player object acts based on other current events. Whenever
the player pushes movement keys, the
onStateChange(newState);
function is
called. The code then checks to make sure if the current state is allowed to transition
in to the state defined in
newState
—we wouldn't want the player to start walking
around when dead! If the state change is allowed to occur, then some immediate
code is applied, such as changing the current animation, and then the state is set.
On every
LateUpdate
, the
onStateCycle();
function is called, which allows state
events per engine cycle to occur. This is paced in
LateUpdate
rather than the
Update
function to make sure the input control has been processed first by Unity.
You probably noticed we haven't added all of the states in that code yet. No worries,
we'll keep adding states as needed in the coming chapters.
Apply both the
PlayerStateController
and
PlayerStateListener
scripts to the
player object. Now click on
Play
and… the big moment… press the left or right keys
as assigned in Unity's input setup (which default to
A
and
D
as well as the left
and right arrow keys).
The player moves! You now have a walking character that the player can control!
Pro Tip
Your state system should be flexible and allow new states to be added
easily. This means no state should directly rely on another state but
instead can transition from one state to another. Plan your state systems
in detail and in advance! Some very complex state systems go as far
as having transitional states rather than just cycling states. Games
have used state systems (also known as state machines) for decades,
including in the original Super Mario Bros. games.