touchesBegan错误;无论我在屏幕上触摸什么,游戏都会崩溃

时间:2015-06-09 01:38:00

标签: ios swift optional touchesbegan

所以,我正在为iOS制作一款游戏,除了现在我的touchesBegan功能导致错误之外,所有这些都完成了。这就是我现在的功能:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    var doo = SKAction.removeFromParent()
    /* Called when a touch begins */
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        if GameOver{
            var gameScene = EasyScene(size: self.size)
            gameScene.scaleMode = SKSceneScaleMode.AspectFill
            self.scene!.view?.presentScene(gameScene)
        }
        else{
            if red.containsPoint(location){ // This is Line A
                //takeOut(red)
                red.removeFromParent()
                score++
                scoreNode.text = String(score)
                print("-hi")
            }
            if red1.containsPoint(location){
                red1.removeFromParent()
                score++
                scoreNode.text = String(score)
                //takeOut(red1)
                print("-hel")
            }
            if red2.containsPoint(location){
                red2.removeFromParent()
                score++
                scoreNode.text = String(score)
                //takeOut(red2)
                print("-hell")
            }
            if red3.containsPoint(location){
                red3.removeFromParent()
                score++
                scoreNode.text = String(score)
                //takeOut(red3)
                print("-hello")
            }
            if red4.containsPoint(location){
                red4.removeFromParent()
                //takeOut(red4)
                score++
                scoreNode.text = String(score)
                print("-hellow")
            }
            if red5.containsPoint(location){
                red5.removeFromParent()
                score++
                scoreNode.text = String(score)
                // takeOut(red5)
                print("-hellowor")
            }
            if blue.containsPoint(location){
                GameOver = true
            }
            if blue1.containsPoint(location){
                GameOver = true
            }
            if blue2.containsPoint(location){
                GameOver = true
            }
        }
    }
}

问题是当 GameOver为假时:我在屏幕上触摸的任何内容都会导致崩溃。如果我触摸屏幕(特别是没有spriteNode),它指向标有&#34的行;这是A行和#34;然而,如果我点击屏幕上实际存在的节点,游戏将崩溃并指向我按下的spriteNode说同样的事情:

fatal error: unexpected nil while unwrapping optional value

GameOver == true toouchesBegan工作正常时

1 个答案:

答案 0 :(得分:0)

我的游戏崩溃的原因是因为我已经在我的应用程序初始启动后5秒钟已经编程执行的函数中声明了我的精灵。但是我发现游戏运行正常,因为我的红色精灵是在didMoveToView

中声明的