错误的" func touchesBegan"在迅速

时间:2015-08-20 16:04:05

标签: xcode swift fatal-error

好吧所以我还在学习swift,我的游戏遇到了崩溃错误,当我触摸屏幕使地面移动时,应用程序崩溃了。错误是绿色,它表示"致命错误:在解开一个Optional值时意外发现nil"错误显示在GameScene.swift的第27行(接近底部)这是GameScene代码

import SpriteKit


class GameScene: SKScene {

 var movingGround: AWMovingGround!

  override func didMoveToView(view: SKView) {
    backgroundColor = UIColor.blueColor()

    let movingGround = AWMovingGround (size: CGSizeMake(view.frame.width,20 ))
    movingGround.position = CGPointMake( 0, view.frame.size.height/2)
    addChild(movingGround)

}

**ERROR HIGHLIGHTS "movingGround.start()"**
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    movingGround.start()

}

    override func update(currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */
 }
}

这是移动地面的代码(AWMovingGround)

import Foundation
import SpriteKit

class AWMovingGround: SKSpriteNode {

let NUMBER_OF_SEGMENTS = 20
let COLOR_ONE = UIColor.greenColor()
let COLOR_TWO = UIColor.brownColor()

init (size: CGSize){
    super.init(texture: nil , color: UIColor.redColor(), size: CGSizeMake(size.width*2, size.height))
    anchorPoint = CGPointMake(0,0.5)
    for var i = 0; i < NUMBER_OF_SEGMENTS; i++ {
        var segmentColor = UIColor()
        if i % 2 == 0{
            segmentColor = COLOR_ONE
        }else{
            segmentColor = COLOR_TWO
        }
        let segment = SKSpriteNode(color: segmentColor, size: CGSizeMake(self.size.width / CGFloat(NUMBER_OF_SEGMENTS), self.size.height))
        segment.anchorPoint = CGPointMake(0, 0.5)
        segment.position = CGPointMake(CGFloat(i)*segment.size.width, 0)
        addChild(segment)


    }

}
required init?(coder aDecoder:NSCoder){
    fatalError(" init(coder:) has not been implimented")

}

 func start(){
    let moveleft = SKAction.moveByX(-frame.size.width/2, y: 0,          duration: 1.0)
    runAction(moveleft, completion: nil)
}
}

1 个答案:

答案 0 :(得分:2)

就在这里......

你声明移动地面

var movingGround: AWMovingGround!

但是从不分配给它,而是创建一个本地作用域和同名的版本,这是合法且有效的语法。

override func didMoveToView(view: SKView) {
...
let movingGround = AWMovingGround (size: CGSizeMake(view.frame.width,20 ))
...
}

所以你想要的是......

var movingGround: AWMovingGround!

  override func didMoveToView(view: SKView) {
    backgroundColor = UIColor.blueColor()

    movingGround = AWMovingGround (size: CGSizeMake(view.frame.width,20 ))
    movingGround.position = CGPointMake( 0, view.frame.size.height/2)
    addChild(movingGround)

}