你在正確的軌道上。在GameScene中添加狀態機變量並初始化它的開始狀態。
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var stateMachine: GKStateMachine!
override func didMove(to view: SKView) {
self.stateMachine = GKStateMachine(states: [
StartState(scene: self),
PlayingState(scene: self),
PausedState(scene: self),
GameOverState(scene: self)
])
self.stateMachine.enter(StartState.self)
}
override func update(_ currentTime: TimeInterval) {
self.stateMachine.update(deltaTime: currentTime)
}
}
,使他們接受GameScene作爲輸入參數,然後初始化狀態。
import SpriteKit
import GameplayKit
class StartState: GKState {
var scene: GameScene!
init(scene: GameScene){
super.init()
self.scene = scene
}
override func isValidNextState(_ stateClass: Swift.AnyClass) -> Bool {
return stateClass == PlayingState.self
}
override func updateWithDeltaTime(seconds: TimeInterval) {
self.stateMachine?.enterState(PlayingState.self)
}
}
我發現[本文](https://medium.com/swift-programming/build-tic-tac-toe-with-ai-using-swift-25c5cd3085c9#.6hyeh3v9j)解釋'GKStateMachine'對於將邏輯放入每個狀態的細節都相當好。 –