ios - 让 Spritekit 显示存储在变量中的整数

标签 ios swift sprite-kit

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

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. 是非法的,因为您不能将 StringInt
  4. 相加

解决方案

这段代码应该可以完成工作

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 节点内文本的更新。

希望这对您有所帮助。

关于ios - 让 Spritekit 显示存储在变量中的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32749009/

相关文章:

ios - 像素图像背景大小 Sprite Kit Game

ios - 无法使用 '[NSAttributedString.Key : Any]' 类型的参数为 'String' 类型的值添加下标

iOS 7 - 检测哪个 textField 从另一个函数中突出显示

swift - 无法在 Swift 中从该设备复制符号

swift - 我是否需要释放一个 UnsafeBufferPointer 或在缓冲区指针的起始内存位置使用的 UnsafePointer?

swift - 为什么我的 SKTileMapNode 类型的对象没有被解码?

ios - 从 viewDidLoad() 函数中删除 super.viewDidLoad()

ios - 因为不理解 'm' 标志

string - SWIFT:大写字符串的性能

swift - spritekit碰撞检测不一致(无法获取两个节点的位置)