在场景之间传递数据(SpriteKit)

时间:2015-07-28 15:10:39

标签: ios iphone swift sprite-kit

如何将SpriteKit中的信息从一个场景传递到另一个场景?在我的游戏中,我有两个场景,GameScene和GameOverScene。当分数增加时,分数会显示在GameScene中,但如何将此信息发送到第二个场景?

当玩家用尽生活而改变场景时,会调用此功能。

 func changeScene(){

    let secondScene = GameOverScene(size: self.size)
    secondScene.scaleMode = scaleMode
    let transition = SKTransition.fadeWithDuration(0.5)
    self.view?.presentScene(secondScene, transition: transition)
}

这是我的gameOverScene

class GameOverScene: SKScene {

var playAgainLabel = SKLabelNode(fontNamed:"Chalkduster")
var currentScore: Int
var scoreLabel = SKLabelNode(fontNamed: "Chalkduster")
var highScore = 0
var highScoreLabel = SKLabelNode(fontNamed: "Chalkduster")
var gameScene = GameScene()
override func didMoveToView(view: SKView) {

    backgroundColor = SKColor.blackColor()

    playAgainLabel.text = "Click To Play Again!"
    playAgainLabel.fontSize = 30
    playAgainLabel.fontColor = SKColor.whiteColor()
    playAgainLabel.position = CGPoint(x: frame.width / 2, y: frame.height / 2)
    self.addChild(playAgainLabel)

    if currentScore > highScore {
        highScore = currentScore
    }

    scoreLabel.text = "Score: " + String(currentScore)
    scoreLabel.fontSize = 20
    scoreLabel.fontColor = SKColor.whiteColor()
    scoreLabel.position = CGPoint(x: frame.width/2, y: frame.height/1.4)
    self.addChild(scoreLabel)

    highScoreLabel.text = "Best: " + String(highScore)
    highScoreLabel.fontSize = 20
    highScoreLabel.fontColor = SKColor.whiteColor()
    highScoreLabel.position = CGPoint(x: frame.width / 2, y: frame.height / 1.6)
    self.addChild(highScoreLabel)

}


override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)

    let playingScene = GameScene(size: self.size)
    playingScene.scaleMode = scaleMode
    let fadeTransition = SKTransition.fadeWithDuration(0.5)
    self.view?.presentScene(playingScene, transition: fadeTransition)
}

} }

2 个答案:

答案 0 :(得分:6)

For instance, your GameOverScene could be something like this:

class GameOverScene: SKScene {
    var object: SomeObject!
}

Now, in your changeScene:

func changeScene(){
    let secondScene = GameOverScene(size: self.size)
    secondScene.scaleMode = scaleMode

    secondScene.object = somethingInFirstSceneThatNeedToBePassed //here we do the passing

    let transition = SKTransition.fadeWithDuration(0.5)
    self.view?.presentScene(secondScene, transition: transition)
}

答案 1 :(得分:0)

Subclass SKScene and create a new initializer with arguments that you want to pass. As you transition from GameScene to second scene, create second scene by using the initializer you created and pass the score. Then present the second scene.