Search code examples
swiftfunctionsprite-kitswift3scene

Swift 3 my game over code doesn't work correctly


If I touch besides of the buttons the game crash down. What can I do? And how? I want to ignore all touches which is besides of the buttons. How can I do that? Here is my touchesBegan:

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    if let location = touch?.location(in: self),
        let node = self.nodes(at: location).first {

        var player = SKSpriteNode()

        if node.name == "BlueButton" {
            player = playerB
            playerB.isHidden = false

        } else if node.name == "RedButton" {
            player = playerR
            playerR.isHidden = false

        } else if node.name == "YellowButton" {
            player = playerY
            playerY.isHidden = false

        } else if node.name == "GreenButton" {
            player = playerG
            playerG.isHidden = false

        }
        for sprite in [playerB, playerW, playerR, playerY, playerG] {
            sprite?.removeFromParent()
        }
        player.position = CGPoint(x: 0, y: -60)
        addChild(player)
    }

}

Here is my touchesEnded function

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    addChild(playerW)
    playerB.removeFromParent()
    playerR.removeFromParent()
    playerY.removeFromParent()
    playerG.removeFromParent()

}

Solution

  • From the discussion in my other answer I guess that the complexity of your touchesBegan leads you to add more than one version of a player-sprite occasionally. The below should only add each playerSprite once and only one at a time which should make it easier to avoid unintended contacts due to sprites covering sprites etc...

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        if let location = touch?.location(in: self),
            let node = self.nodes(at: location).first {
    
            var player = SKSpriteNode()
    
            if node.name == "BlueButton" {
                player = playerB
            } else if node.name == "RedButton" {
                player = playerR
            } else if node.name == "YellowButton" {
                player = playerY
            } else if node.name == "GreenButton" {
                player = playerG
            }
            for sprite in [playerB, playerW, playerR, playerY, playerG] {
                sprite.removeFromParent()
            }
            player.position = CGPoint(x: 0, y: -50)
            addChild(player)
        }
    }