Set Up the Player State Machine

In GameplayKit, you use the GKStateMachine superclass to create state machines. A state machine holds the list of possible states, the current state, and some logic for moving between the states.

For Val’s Revenge, you’ll create a player state machine that controls the player’s state, specifically for tracking when players have a key versus when they don’t.

In the Project Navigator, switch to the Player.swift file. Below the line that reads import SpriteKit, add the following new import statement to import the GameplayKit framework:

 import​ ​GameplayKit

Next, you need a property to hold the state machine for the Player class. Add the following code at the top of the Player class, just above the currentDirection property declaration:

 var​ stateMachine = ​GKStateMachine​(states: [​PlayerHasKeyState​(),
 PlayerHasNoKeyState​()])

This code creates a single state machine, initialized with the two player states you created earlier.

The next step is to set the initial state for the player state machine. In Creating the Player Class, you created the bare minimum required to get the Player class working. Since you’re adding the player sprite node using the Scene Editor, you can override the init(coder:) method and set the default state there. Above the move(_:) method, add the following new method to the Player class:

 // Override this method to allow for a class to work in the Scene Editor
 required​ ​init​?(coder: ​NSCoder​) {
 super​.​init​(coder: coder)
 
  stateMachine.​enter​(​PlayerHasNoKeyState​.​self​)
 }

(While you’re here, comment out the print() statement in the move(_:) method.)

There’s not much going on with this code: you’re using the enter(_:) method of the GKStateMachine class to enter the specified state: PlayerHasNoKeyState. It makes sense to start Val without a key, giving her the immediate challenge of finding one so that she can explore deeper into the dungeon.

Build and run the project. Look at the console and you’ll see something like this:

 Entering PlayerHasNoKeyState

With this confirmation, you now know you have a new initialization method that gets called when the player node is added to the scene. This same method also sets the initial state of the player; however, you still need to define the collectible items—for that, you’ll create a new collectible component.

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

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