1. 在Types.swift中通過(guò)枚舉定義初始化、開(kāi)始贮聂、游戲中靠柑、勝利、失敗吓懈、重新加載及暫停
enum GameState:Int {
case initial = 0, start, play, win, lose, reload, pause
}
2. 本教程中的幾種狀態(tài)相對(duì)簡(jiǎn)單歼冰,每種狀態(tài)都會(huì)包含一些label,所以我們?cè)谇袚Q狀態(tài)時(shí)耻警,只需先將原狀態(tài)的label移除隔嫡,再添加新的label即可,移除原狀態(tài)的label及添加新?tīng)顟B(tài)的label方法如下(移除的方法就是直接通過(guò)text查找到相應(yīng)的對(duì)象并予以移除):
//移除對(duì)象
private func remove(message:String) {
childNode(withName: message)?.removeFromParent()
}
//移除原狀態(tài)的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
}
}
//添加新?tīng)顟B(tài)的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. 創(chuàng)建updateGameState的方法切換游戲狀態(tài)
func updateGameState(from:GameState, to: GameState) {
clearUI(gameState: from)
updateUI(gameState: to)
}
4. 在GameScene中新建成員變量gameState并初始化為.initial狀態(tài)甘穿,然后建立監(jiān)聽(tīng)機(jī)制:
var gameState:GameState = .initial {
didSet {
hud.updateGameState(from: oldValue, to: gameState)
}
}
didSet是在屬性值改變以后執(zhí)行方法腮恩,willSet是在屬性值改變之前執(zhí)行方法
5. 在游戲開(kāi)始后,游戲狀態(tài)為start温兼,所以需要在didMove中將gameState設(shè)置為.start
gameState = .start
6. 本教程中需要完成以下需求:通過(guò)點(diǎn)擊屏幕秸滴,完成.start ->.play及.lose->.start的切換。倒計(jì)時(shí)結(jié)束后自動(dòng)完成.play->.lose的切換募判。
通過(guò)點(diǎn)擊屏幕荡含,完成.start ->.play及.lose->.start的切換。
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
switch gameState {
//start狀態(tài)時(shí)届垫,點(diǎn)擊屏幕内颗,1.游戲狀態(tài)切換為play 2. isPaused狀態(tài)變?yōu)椴粫和#磃alse 3. startTime初始化為nil 4. elapsedTime初始化為0
case .start:
gameState = .play
isPaused = false
startTime = nil
elapsedTime = 0
//play狀態(tài)時(shí)敦腔,點(diǎn)擊屏幕均澳,player可以移動(dòng)
case .play:
player.move(target: touch.location(in: self))
//lose狀態(tài)時(shí),點(diǎn)擊屏幕符衔,切換為start狀態(tài)
case .lose:
gameState = .start
default:
break
}
}
倒計(jì)時(shí)結(jié)束后自動(dòng)完成.play->.lose的切換找前。
首先我們需要檢測(cè)什么時(shí)候狀態(tài)滿足lose的條件,即倒計(jì)時(shí)為0時(shí)
滿足條件后將gameSate = .lose即可
func checkEndGame() {
// if bugNode.children.count == 0 {
// gameState = .win
// }
if timeLimit - elapsedTime <= 0 {
gameState = .lose
}
}
因?yàn)闄z測(cè)是實(shí)時(shí)的判族,所以將checkEndGame()添加到update方法中躺盛。