【问题标题】:How can I increase and display the score every second?如何每秒增加和显示分数?
【发布时间】:2018-03-20 03:17:59
【问题描述】:

我正在用 Swift 制作 SpriteKit 游戏。而gameState = inGame,我希望分数每秒都在增加。我将如何以及在哪里计算和显示这样的东西?

我发现的其他答案已经过时并且不是很有帮助。可能有一个我不知道的已经存在,所以如果你能指出我的方向,我将不胜感激。感谢您的帮助。

【问题讨论】:

  • "我找到的其他答案" 不要放 'the.'你没有提到任何。我建议你修改问题。没有人知道你所说的“分数”。那是一个 SKLabelNode 对象吗?一个整数?

标签: swift xcode timer sprite-kit


【解决方案1】:

正如您所描述的,这是一种每秒递增和显示分数的非常简单的方法。

此处的“计时器”将与您游戏的帧速率相关联,因为在更新方法中检查了计数器,该更新方法可能因您的帧速率而异。如果您需要更准确的计时器,请考虑使用 Timer 类并搜索 Stack Overflow 或 Google 以了解如何使用它,因为它可能比这里的简单的更复杂。

要对此进行测试,请在 Xcode 中创建一个新的游戏模板项目,并将 GameScene.swift 文件的内容替换为以下代码。

您实际上并不需要使用gameStateIsInGame 的部分。我只是把它放在那里作为演示,因为你说要检查一些gameState 属性以触发计时器。在您自己的代码中,您可以集成自己的 gameState 属性,但您正在处理它。

import SpriteKit

class GameScene: SKScene {
    var scoreLabel: SKLabelNode!
    var counter = 0
    var gameStateIsInGame = true
    var score = 0 {
        didSet {
            scoreLabel.text = "Score: \(score)"
        }
    }

    override func didMove(to view: SKView) {
        scoreLabel = SKLabelNode(fontNamed: "Chalkduster")
        scoreLabel.text = "Score: 0"
        scoreLabel.position = CGPoint(x: 100, y: 100)
        addChild(scoreLabel)
    }

    override func update(_ currentTime: TimeInterval) {
        if gameStateIsInGame {
            if counter >= 60 {
                score += 1
                counter = 0
            } else {
                counter += 1
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-05
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多