让Spritekit显示一个存储在变量中的整数



所以我很难做一些应该很容易的事情,显然我看不出有什么问题。这是代码:

import SpriteKit
var money = "0"
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
    /* Setup your scene here */
    let moneyLabel = SKLabelNode(fontNamed:"Times New Roman")
    moneyLabel.text = money;
    moneyLabel.fontSize = 14;
    moneyLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));
    self.addChild(moneyLabel)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
   /* Called when a touch begins */
    for touch in touches {
        money + 1
    }
}
override func update(currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */
}

}

这应该做的是让一个标签显示一个变量,当用户触摸屏幕时,变量变化1,每次按下1。标签应该随着变量的变化而变化。我该怎么做呢?

问题

您只是将1添加到money

money + 1
这个代码:

  1. 不改变money属性
  2. 不改变您的moneyLabel
  3. 中的文本
  4. 是非法的,因为你不能对StringInt求和

解决方案

这段代码应该完成

import SpriteKit
class GameScene: SKScene {
    private var money = 0 {
        didSet {
            self.moneyLabel?.text = money.description
        }
    }
    private var moneyLabel : SKLabelNode?
    override func didMoveToView(view: SKView) {         
        let moneyLabel = SKLabelNode(fontNamed:"Times New Roman")
        moneyLabel.text = money.description
        moneyLabel.fontSize = 14
        moneyLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
        self.addChild(moneyLabel)
        self.moneyLabel = moneyLabel
    }
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        money += touches.count
    }
}

解释

1)

您可以看到,我在money属性中添加了一个观察者(顺便说一下,我使它成为Int属性,而不是您代码中的String !)

didSet {
    self.moneyLabel?.text = money.description
}

由于观察者的作用,每次货币发生变化时,moneyLabel节点都会被检索并更新其文本。

2)

didMoveToView结束时,我将moneyLabel保存到实例属性

self.moneyLabel = moneyLabel

,这样我就可以很容易地检索到

(我们在前面已经看到了)

3)

最后在touchesBegan中,我只是将money属性增加接收触摸的数量。

money += touches.count

多亏了观察者,每次对money属性的更改都会触发对moneyLabel节点内文本的更新。

这里有三个问题:

  1. money应该是一个Int,所以你可以添加。
  2. 您实际上没有将money更新为新值。
  3. 除了money之外,您还需要更新标签。

看看下面的变化;每个注释解释了为什么需要更改:

import SpriteKit
class GameScene: SKScene {
    var money = 0 //now an Int, so we can add to it later
    let moneyLabel = SKLabelNode(fontNamed:"Times New Roman") //keep this around so we can update it later
    override func didMoveToView(view: SKView) {
        moneyLabel.text = String(money) //convert money to a String so we can set the text property to it
        moneyLabel.fontSize = 14
        moneyLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
        self.addChild(moneyLabel)
    }
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for touch in touches {
            money = money + 1 //update money to itself + 1
            moneyLabel.text = String(money) //update the label, too
        }
    }
}

最新更新