首页 > 解决方案 > 当玩家点击屏幕开始游戏时如何开始基于时间的得分

问题描述

我一直在关注这个解决方案(我如何每秒增加和显示分数?)根据经过的时间为我的游戏添加分数。我让它完美地工作;当玩家输球时,分数停止,当玩家重新开始游戏时,分数重新回到 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:但都没有奏效。

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

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

关于如何解决这个小问题的任何想法?我似乎无法弄清楚。

****编辑****

这是更新的覆盖函数更新方法。我摆脱if gameStateIsInGame {}并添加了if counter >= 10下面的声明if gameState

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

标签: iosswift

解决方案


简化的解决方案

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

  override func update(_ currentTime: TimeInterval) {

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

推荐阅读