是否可以更新SKLabelNode?

时间:2016-09-30 22:48:37

标签: swift swift3 sklabelnode

我正在尝试更新coinLabel,以便在点击“生命”节点时,它将更新SKLabelNode并在从总数中减去后显示正确的硬币。我是编码的新手,所以如果有任何其他问题请回复!谢谢!

import Foundation
import SpriteKit

class ShopScene: SKScene {

override func didMove(to view: SKView) {


    let background = SKSpriteNode(imageNamed: "background")
    background.size = self.size
    background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
    background.zPosition = 0
    self.addChild(background)

    let mainMenu = SKLabelNode(fontNamed: "The Bold Font")
    mainMenu.text = "Main Menu"
    mainMenu.fontSize = 100
    mainMenu.fontColor = SKColor.darkGray
    mainMenu.position = CGPoint(x: self.size.width*0.5, y: self.size.height*0.3)
    mainMenu.zPosition = 1
    mainMenu.name = "Main Menu"
    self.addChild(mainMenu)

    let Life = SKLabelNode(fontNamed: "The Bold Font")
    Life.text = "Click here to buy 1 life!"
    Life.fontSize = 130
    Life.fontColor = SKColor.darkGray
    Life.position = CGPoint(x: self.size.width*0.5, y: self.size.height*0.6)
    Life.zPosition = 1
    Life.name = "Life"
    self.addChild(Life)

    let coinLabel = SKLabelNode(fontNamed: "The Bold Font")
    coinLabel.text = "Coins: \(coinNumber)"
    coinLabel.fontSize = 100
    coinLabel.fontColor = SKColor.black
    coinLabel.zPosition = 1
    coinLabel.position = CGPoint(x: self.size.width/2, y: self.size.height*0.1)
    self.addChild(coinLabel)



}


override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {


    for touch: AnyObject in touches {

        let pointOfTouch = touch.location(in: self)
        let nodeITapped = atPoint(pointOfTouch)

        if nodeITapped.name == "Main Menu" {


            let sceneToMoveTo = MainMenuScene(size: self.size)
            sceneToMoveTo.scaleMode = self.scaleMode
            let myTrasition = SKTransition.fade(withDuration: 0.5)
            self.view!.presentScene(sceneToMoveTo, transition: myTrasition)
        }

            if nodeITapped.name == "Life" {
                if coinNumber > 10 {
                lifeNumber += 1
                coinNumber -= 10
                defaults.set(coinNumber, forKey: "coinNumberSaved")
                defaults.set(lifeNumber, forKey: "lifeNumberSaved")


                return

                }


            }
        }


    }


}

1 个答案:

答案 0 :(得分:0)

只需再次更新点击识别器中的文字即可进行更改

coinLabel.text = "Coins: \(coinNumber)"

您需要确保在init之外引用coinLabel,以便在其外部操作它。 在ShopScene的顶部你可以做...

class ShopScene: SKScene {
var coinLabel = SKLabelNode()
//your code
}

然后当你在didMove中转到init(查看:) func时,请改为......

 coinLabel = SKLabelNode(fontNamed: "The Bold Font")

通过这种方式,您可以在整个代码中引用它。虽然将来你会考虑制作一个SKNode的子类来处理你所有的UI元素,这样你就不会在你的GameScene中初始化所有内容。