ios - 当玩家点击屏幕开始游戏时如何开始基于时间的计分

标签 ios swift

我一直在遵循这个解决方案( How can I increase and display the score every second? ),根据耗时为我的游戏添加评分。我让它工作得很好;当玩家输了时,分数会停止;当玩家重新开始游戏时,分数会重新回到 0。

但是,“计时器”会在用户点击开始之前自动开始,并且我试图在玩家点击游戏开始玩时启动“计时器”(用户首先必须点击屏幕开始运行,开始游戏)。

在我的 didMove 方法中,我有

scoreLabel = SKLabelNode(fontNamed: "Press Start K")
scoreLabel.text = "Score: 0"
scoreLabel.position = CGPoint(x: 150.0, y: 620.0)
scoreLabel.zPosition = GameConstants.ZPositions.hudZ

addChild(scoreLabel)

在我的重写函数更新方法中,我有

if gameStateIsInGame {
    if counter >= 10 {
        score += 1
        counter = 0
    } else {
        counter += 1
    } 
}

我认为通过将 if gameStateIsInGame {} 添加到touchesBegan 方法中,它会在用户点击屏幕时启动,但这不起作用。我尝试将其添加到 case.ready:case.ongoing: 下,但都不起作用。

这是我在 TouchBegan 方法顶部的内容。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    switch gameState {
    case .ready:
        gameState = .ongoing
        spawnObstacles()

    case .ongoing:
        touch = true
        if !player.airborne {
            jump()
            startTimers()
        }
    }
}

关于如何解决这个小问题有什么想法吗?我似乎无法弄清楚。

****编辑****

这是更新后的 override func 更新方法。我删除了 if gameStateIsInGame {} 并在 if gameState 下添加了 if counter >= 10 语句。

    override func update(_ currentTime: TimeInterval) {
    if lastTime > 0 {
        dt = currentTime - lastTime
    } else {
        dt = 0
    }
    lastTime = currentTime

    if gameState == .ongoing {
        worldLayer.update(dt)
        backgroundLayer.update(dt)
        backgroundGround.update(dt)
        backgroundSunset.update(dt)
        if counter >= 10 {
            score += 1
            counter = 0
        } else {
            counter += 1
        }
    }
}

最佳答案

简化的解决方案

在覆盖功能更新下添加了分数计数器。

  override func update(_ currentTime: TimeInterval) {

        if gameState == .ongoing {
            if counter >= 10 {
                score += 1
                counter = 0
            } else {
                counter += 1
            }
        }
}

关于ios - 当玩家点击屏幕开始游戏时如何开始基于时间的计分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56193428/

相关文章:

ios - SwiftUI 通过 TabView 以模态方式呈现 View ?

ios - 快速从json获取位置

ios - 未选中时无法更改按钮颜色

ios - 如何在 iOS 中隐藏或更改特定设备的布局

iphone - 我可以使用 UIImagePickerController 拍多张照片吗?

iOS 8.3 共享扩展 - 启动 URL 方案

swift - 如何在 SceneKit 中反转球体的法线?

ios - 混合 objective-c 项目中的 Swift "namespaces"不工作

ios - 按下时更改以编程方式创建的按钮的颜色

ios - 带有 SDK 绝对路径的 xcodebuild 命令