Search code examples
sprite-kitgameplay-kit

How can I use GameplayKit State Machine for sprite animation?


I have two animations for my player to run and jump. Can I control these animations using GameplayKit's state machines? If so, how? In this project, I use SpriteKit and GameplayKit for Entity-Component architecture and State Machine.


Solution

  • You need set first the StateMachine and fill with your custom classes

    self.playerStateMachine = GKStateMachine(states: [
        PlayerRunning(player),
        PlayerJumping(player)
    ])
    

    Then when you need to enter to state, can be with:

    self.playerStateMachine?.enter(PlayerRunning.self)
    

    On the state you can perform changes like:

    override func didEnter(from previousState: GKState?) {
        self.player?.run(runAnimation)
    }
    

    Example:

    enter image description here

    Please take a look of complete example here: https://github.com/Maetschl/SpriteKitExamples/blob/master/StateMachineAnimation/StateMachineAnimation/GameScene.swift