本文介绍了如何每秒增加和显示分数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am making a SpriteKit game in Swift. While gameState = inGame, I want the score to increase every second. How and where would I calculate and display something like this?

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

The other answers I have found are outdated and not very helpful. There might be one I am not aware of that already exists, so I would be greatly appreciative if you could point me in that direction. Thanks for the help.

推荐答案

这是一种非常简单的方法,可以按照您的描述,每秒递增和显示一个分数.

Here is a very simple way of incrementing and displaying a score every second, as you have described it.

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

The "timer" here will be tied to your game's framerate because the counter is checked in the update method, which can vary based on your framerate. If you need a more accurate timer, consider the Timer class and search Stack Overflow or Google to see how to use it, as it can be more complicated than the simple one here.

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

To test this, create a new Game template project in Xcode and replace the contents of your GameScene.swift file with the following code.

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

You don't actually need the parts that use gameStateIsInGame. I just put that in there as a demonstration because of your remark about checking some gameState property in order for the timer to fire. In your own code you would integrate your own gameState property however you are handling it.

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
            }
        }
    }
}

这篇关于如何每秒增加和显示分数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 18:55