Vladislav Kulikov
Vladislav Kulikov

Reputation: 465

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.

Upvotes: 0

Views: 317

Answers (1)

Maetschl
Maetschl

Reputation: 1339

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

Upvotes: 1

Related Questions