I've been following this solution (How can I increase and display the score every second?) to add scoring to my game based on how much time has passed. I have it working perfectly; the score stops when the player loses and it restarts back to 0 when the player restarts the game.

However, the "timer" begins automatically before the user taps to begin, and I'm trying to have the "timer" start when the player taps on the game to begin playing (the user first has to tap on the screen to start running, beginning the game).

In my didMove method, I have

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)

and in my override func update method, I have

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

I figured that by adding the if gameStateIsInGame {} to the touchesBegan method, it would start when the user taps on the screen but that didn't work. I tried adding it under case.ready: and under case.ongoing: but neither worked.

This is what I have at the top of my touchesBegan method.

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

Any ideas on how to fix this small issue? I can't seem to figure it out.

****EDIT****

Here's the updated override func update method. I got rid of if gameStateIsInGame {} and added the if counter >= 10 statement under 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
        }
    }
}

1 Answers

0
Community On

Simplified Solution

Added the score counter under override func update.

  override func update(_ currentTime: TimeInterval) {

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