正如@Knight0fDragon 所建议的,您最好使用GKStateMachine 功能,我会给您举个例子。
首先声明你的玩家/角色在你的场景中的状态
lazy var playerState: GKStateMachine = GKStateMachine(states: [
Idle(scene: self),
Run(scene: self)
])
然后你需要为这些状态中的每一个创建一个类,在这个例子中我将只向你展示Idle类
import SpriteKit
import GameplayKit
class Idle: GKState {
weak var scene: GameScene?
init(scene: SKScene) {
self.scene = scene as? GameScene
super.init()
}
override func didEnter(from previousState: GKState?) {
//Here you can make changes to your character when it enters this state, for example, change his texture.
}
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
return stateClass is Run.Type //This is pretty obvious by the method name, which states can the character go to from this state.
}
override func update(deltaTime seconds: TimeInterval) {
//Here is the update method for this state, lets say you have a button which controls your character velocity, then you can check if the player go over a certain velocity you make it go to the Run state.
if playerVelocity > 500 { //playerVelocity is just an example of a variable to check the player velocity.
scene?.playerState.enter(Run.self)
}
}
}
当然,在您的场景中,您需要做两件事,首先是将角色初始化为某个状态,否则它将保持无状态,因此您可以在 didMove 方法中进行此操作。
override func didMove(to view: SKView) {
playerState.enter(Idle.self)
}
最后但同样重要的是确保场景更新方法调用状态更新方法。
override func update(_ currentTime: TimeInterval) {
playerState.update(deltaTime: currentTime)
}