我要实现的目标是一个精灵套件游戏(已经完成),其中包含玩家的生命。首次玩游戏时,游戏会以3种生命开始,并将此值保存到firebase并显示在我的游戏场景中的SKLabelNode中。我希望能够从该值中减去并更新标签和数据库值。
此外,我还希望在生命== 0时展示奖励视频广告(来自AdMob)。
到目前为止,我关于生命的代码是:
let ref = Database.database().reference()
let userID = Auth.auth().currentUser?.uid
ref.child("userLives").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot)
// Get user life value
guard let firebaseResponse = snapshot.value as? [String:Any] else {
print("Snapshot is nil, no data will be returned")
return
}
let livesNumber = firebaseResponse["lives"] as! Int
self.livesLabel.text = "Lives: \(livesNumber)"
}) { (error) in
print(error.localizedDescription)
}
self.addChild(livesLabel)
}
此代码正确显示用户开始使用的生命值“ 3”。以下是得分的代码,当游戏结束时,这是我假设我将更改生命值的地方。为了更改数据库中的值并将其重新显示到SKLabelNode,它会是什么样?
func didBegin(_ contact: SKPhysicsContact) {
let firstBody = contact.bodyA
let secondBody = contact.bodyB
if firstBody.categoryBitMask == PhysicsCategory.Score && secondBody.categoryBitMask == PhysicsCategory.Ghost || firstBody.categoryBitMask == PhysicsCategory.Ghost && secondBody.categoryBitMask == PhysicsCategory.Score {
score+=1
scoreLbl.text = "\(score)"
}
**if firstBody.categoryBitMask == PhysicsCategory.Ghost && secondBody.categoryBitMask == PhysicsCategory.Wall || firstBody.categoryBitMask == PhysicsCategory.Wall && secondBody.categoryBitMask == PhysicsCategory.Ghost {
died = true
createBtns()
//add in function that takes 1 away from the lives value (HERE)**
ref = Database.database().reference()
if score > Highscore {
let HighscoreDefault = UserDefaults()
Highscore = score
HighscoreDefault.set(Highscore, forKey: "Highscore")
ref = Database.database().reference(fromURL: "https://clickcounterx.firebaseio.com/")
let userId = Auth.auth().currentUser?.uid
let UsersName = Auth.auth().currentUser?.displayName
self.ref.child("userScoresFlappy").child(userId!).setValue(["Name": UsersName!, "Score": Highscore])
}
}
}