1
votes

In my game, I want a game over label to appear when the screen is touched during the red light animation. The red light animation is on when the green light animation is off. I want the game screen to pause and the game over label to appear when the player touches the screen during the red light animation. I have this so far, but the app crashes when I try to run it.

Error Message:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attemped to add a SKNode which already has a parent: name:'(null)' text:'Game Over! Tap to Play Again' fontName:'Helvetica' position:{1024, 768}'

 override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    /* Called when a touch begins */


    if gameOverLabel.parent == nil
    {
        self.addChild(gameOverLabel)
    }

    println(score)

    scoreLabel.text = "\(score)"
}
1
post crash message and highlight line of code that crashes. Is it possible that gameOverLabel is already in the hierarchy when you run addChild with it? - LearnCocos2D
I added the error message in the original post. - D.Khan
No offense, but have you read the error message? Looks pretty clear to me. You should use removeFromParent at some point. - Matthias Bauch
Yes I read it, but didn't know how to go about solving the issue. I wrote the line of code 'gameOverLabel.removeFramParent()'. But the gameOverLabel still does not appear when the screen is touched during the redLight animation. - D.Khan
can you show the complete code where you initialise the gameOverLabel ? - rakeshbs

1 Answers

0
votes

Try this. You were setting the gameOverLabel with a font size that was too big and frame that was outside the screen. This was why it was not visible. Also you have to stop the game when it reaches game over.

if (!self.paused)
{
    if isGreenLightON
    {
        score += 50
    }
    else
    {
        self.paused = true

        if (gameOverLabel.parent != nil)
        {
            gameOverLabel.removeFromParent()
        }
        gameOverLabel.fontName = "Helvetica"
        gameOverLabel.fontColor = UIColor.blackColor()
        gameOverLabel.fontSize = 24
        gameOverLabel.text = "Game Over! Tap to Play Again"
        gameOverLabel.position = CGPointMake(CGRectGetMidX(self.frame), self.frame.size.height - 50)
        self.addChild(gameOverLabel)
    }
}
else
{
    score = 0
    if (gameOverLabel.parent != nil)
    {
        gameOverLabel.removeFromParent()
    }
    self.paused = false
}
scoreLabel.text = "\(score)"