Search code examples
swiftif-statementsprite-kitgame-physicsstatements

override func update problems, in swift


I'm currently using the following code to monitor my game state:

override func update(currentTime: CFTimeInterval) {

    // Game over query //

    if car.physicsBody?.angularVelocity < 10  {carFly()}
    else {gameOver()}
}

This appears to work well and does not tax the CPU at all (which is pleasing). However, the function gameOver() is never called just once... It calls multiple times which leads to jerky transitions / weird behaviour.

How can structure this so that it calls gameOver() just once?


Solution

  • You can add Bool flag to control this situation like this for example:

    ...
    var isGameOver: Bool = false
    ...
    override func update(currentTime: CFTimeInterval) {
    
        // Game over query //
    
        if car.physicsBody?.angularVelocity < 10  {
            carFly()
        } else {
            if isGameOver {
                return
            } else {
                isGameOver = true
                gameOver()
            }
        }
    }