State machines are easy. If you want an overview, I’ll defer (again) to Game Programming Patterns.
The GKState interface is really straightforward:
Apple went again with Class instances as identifiers for states, as it did with components. There’s nothing really tricky in there, except that
-isValidNextState: appears to return YES by default, which feels weird to me:
I’d have gone with NO. I did, actually, and had to change it after I got around to double-checking. :)
GKStateMachine is also straightforward:
Same deal as last time, we can implement this by storing the states in a NSMapTable.
The only interesting bit in this is making sure there’s only one kind of each state type in there, and you can do that by just making sure there’s not an existing value in your map table as you add states to it.
For the demo, I re-implemented the Wander component from last time using a state machine, and added an extra action in there on the sprite that supports it. The state diagram for wandering looks like this: