1. 在Types.swift中通过枚举定义初始化、开始、游戏中、胜利、失败、重新加载及暂停
enum GameState:Int {
case initial = 0, start, play, win, lose, reload, pause
}
2. 本教程中的几种状态相对简单,每种状态都会包含一些label,所以我们在切换状态时,只需先将原状态的label移除,再添加新的label即可,移除原状态的label及添加新状态的label方法如下(移除的方法就是直接通过text查找到相应的对象并予以移除):
//移除对象
private func remove(message:String) {
childNode(withName: message)?.removeFromParent()
}
//移除原状态的label
private func clearUI(gameState:GameState){
switch gameState {
case .start:
remove(message: HUDMessages.tapToStart)
case .win:
remove(message: HUDMessages.win)
remove(message: HUDMessages.nextLevel)
case .lose:
remove(message: HUDMessages.lose)
remove(message: HUDMessages.playAgain)
default:
break
}
}
//添加新状态的label
private func updateUI(gameState:GameState) {
switch gameState {
case .start:
add(message: HUDMessages.tapToStart, position: .zero)
case .win:
add(message: HUDMessages.win, position: .zero)
add(message: HUDMessages.nextLevel,
position: CGPoint(x: 0, y: -100))
case .lose:
add(message: HUDMessages.lose, position: .zero)
add(message: HUDMessages.playAgain, position: CGPoint(x: 0, y: -100))
default:
break
}
}
3. 创建updateGameState的方法切换游戏状态
func updateGameState(from:GameState, to: GameState) {
clearUI(gameState: from)
updateUI(gameState: to)
}
4. 在GameScene中新建成员变量gameState并初始化为.initial状态,然后建立监听机制:
var gameState:GameState = .initial {
didSet {
hud.updateGameState(from: oldValue, to: gameState)
}
}
didSet是在属性值改变以后执行方法,willSet是在属性值改变之前执行方法
5. 在游戏开始后,游戏状态为start,所以需要在didMove中将gameState设置为.start
gameState = .start
6. 本教程中需要完成以下需求:通过点击屏幕,完成.start ->.play及.lose->.start的切换。倒计时结束后自动完成.play->.lose的切换。
通过点击屏幕,完成.start ->.play及.lose->.start的切换。
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
switch gameState {
//start状态时,点击屏幕,1.游戏状态切换为play 2. isPaused状态变为不暂停,即false 3. startTime初始化为nil 4. elapsedTime初始化为0
case .start:
gameState = .play
isPaused = false
startTime = nil
elapsedTime = 0
//play状态时,点击屏幕,player可以移动
case .play:
player.move(target: touch.location(in: self))
//lose状态时,点击屏幕,切换为start状态
case .lose:
gameState = .start
default:
break
}
}
倒计时结束后自动完成.play->.lose的切换。
首先我们需要检测什么时候状态满足lose的条件,即倒计时为0时
满足条件后将gameSate = .lose即可
func checkEndGame() {
// if bugNode.children.count == 0 {
// gameState = .win
// }
if timeLimit - elapsedTime <= 0 {
gameState = .lose
}
}
因为检测是实时的,所以将checkEndGame()添加到update方法中。