我使用Sprite Kit在Swift中制作了一个简单的游戏。
得分和HighScore定义为NSInteger
。播放器点击GameOver后,场景重新开始。
现在我要保存最后一个乐谱并显示在新呈现的场景中。
我只有1个场景(GameScene)。 我怎样才能访问最后一个乐谱并每次跟踪它?
我的代码:
override func didMoveToView(view: SKView) {
//Score System
Score = 0
ScoreLabelNode = SKLabelNode(fontNamed:"04b_19")
ScoreLabelNode.position = CGPoint(x: self.frame.size.width / 2,y: self.frame.size.height / 1.06)
ScoreLabelNode.zPosition = 100
ScoreLabelNode.text = String(Score)
HighScore = 0
let defaults = NSUserDefaults.standardUserDefaults()
HighScore = defaults.integerForKey("highscore")
defaults.synchronize()
HighScoreLabel = SKLabelNode(fontNamed:"04b_19")
HighScoreLabel.fontSize = 30
HighScoreLabel.position = CGPoint(x: TransparentLayer.position.x, y: TransparentLayer.position.y)
HighScoreLabel.zPosition = 100
HighScoreLabel.text = String(format: "Best: %d", HighScore)
self.addChild(HighScoreLabel)
}
func saveHighScore(){
//Update HighScore if currentScore is higher
HighScore = max(Score, HighScore)
//Store in user defaults
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(HighScore, forKey: "highscore")
NSUserDefaults.standardUserDefaults().synchronize()
}
func Restart(){
self.saveHighScore()
let Transition = SKTransition.fadeWithDuration(1.5)
let Scene = GameScene(size: self.frame.size)
scene?.scaleMode = SKSceneScaleMode.AspectFill
self.scene?.view?.presentScene(Scene, transition: Transition)
}
答案 0 :(得分:0)
在lastScore
中创建一个名为GameScene
的媒体资源,并在展示新scene
之前设置该媒体资源。
class GameScene {
var lastScore = 0
override func didMoveToView(view: SKView) {
Score = 0
ScoreLabelNode = SKLabelNode(fontNamed:"04b_19")
ScoreLabelNode.position = CGPoint(x: self.frame.size.width / 2,y: self.frame.size.height / 1.06)
ScoreLabelNode.zPosition = 100
ScoreLabelNode.text = String(score)
HighScore = 0
let defaults = NSUserDefaults.standardUserDefaults()
HighScore = defaults.integerForKey("highscore")
defaults.synchronize()
HighScoreLabel = SKLabelNode(fontNamed:"04b_19")
HighScoreLabel.fontSize = 30
HighScoreLabel.position = CGPoint(x: TransparentLayer.position.x, y: TransparentLayer.position.y)
HighScoreLabel.zPosition = 100
HighScoreLabel.text = String(format: "Best: %d", HighScore)
self.addChild(HighScoreLabel)
}
//Other coder
}
然后在调用presentScene
之前设置得分属性。
let scene = GameScene(size: self.frame.size)
scene?.scaleMode = SKSceneScaleMode.AspectFill
scene.lastScore = score // Set the score here
self.scene?.view?.presentScene(scene, transition: Transition)