Search code examples
iosanimationswifttouchsprite-kit

When the screen is touched, how do I make the game over?


I want a game over screen and the game to stop when the screen is touched during a specific animation.

    let lightTexture = SKTexture(imageNamed: "green light.png")
    let lightTexture2 = SKTexture(imageNamed: "red light.png")

    let animateGreenLight = SKAction.sequence([SKAction.waitForDuration(2.0, withRange: 0.1),   SKAction.animateWithTextures([lightTexture, lightTexture2], timePerFrame: 3)])
    let changeGreenLight = SKAction.repeatActionForever(animateGreenLight)


    let animateRedLight = SKAction.sequence([SKAction.waitForDuration(2.0, withRange: 0.1), SKAction.animateWithTextures([lightTexture, lightTexture2], timePerFrame: 3)])
    let changeRedLight = SKAction.repeatActionForever(animateRedLight)


    let greenLight = SKSpriteNode(texture: lightTexture)
    greenLight.position = CGPointMake(CGRectGetMidX(self.frame), 650)
    greenLight.runAction(changeGreenLight)

    self.addChild(greenLight)

    let redLight = SKSpriteNode(texture: lightTexture2)
    redLight.position = CGPointMake(CGRectGetMidX(self.frame), 650)
    redLight.runAction(changeRedLight)

    self.addChild(redLight)

When the animation for the red light is on the screen, I want it to be game over. Do I have to make an if statement, and if so for what specifically?

Thank You in advance!


Solution

  • You can make yourself another node which has the same size and position as the red light. Additionally, that node is able to handle touch events. Then, add that node before the animation runs. This can be done with a sequence of actions, e.g.:

    let addAction = SKAction.runBlock({ self.addChild(touchNode) })
    let animationAction = SKAction.repeatActionForever(animateRedLight)
    
    redLight.runAction(SKAction.sequence([ addAction, animationAction ]))
    

    Update

    Since you want the game to end when you touch anywhere, alter the code such that the block sets a variable which indicates that the animation is executed and implement touchesBegan which checks for that variable, e.g.

    let addAction = SKAction.runBlock({ self.redLightAnimationRuns = true })
    
    [...]
    
    // In touchesBegan
    if touched
    {
        if redLightAnimationRuns
        {
            endGame()
        }
    }