我试图做到这一点,以便当我在屏幕上某处触摸时,我的精灵会收到冲动和速度,但我收到了错误代码:
致命错误:在解包可选值时意外发现nil
迫使我放一个"!"在" physicsbody"前面,当我这样做时它会崩溃。如果我放一个"?"冲动和速度刚刚起作用。
func setuprocket() {
let rocket0 = SKTexture(imageNamed: "0zero.png")
let rocket1 = SKTexture(imageNamed: "1one.png")
let rocket2 = SKTexture(imageNamed: "2two.png")
let rocket3 = SKTexture(imageNamed: "3three.png")
let rocket4 = SKTexture(imageNamed: "4four.png")
let rocket5 = SKTexture(imageNamed: "5five")
let animateRocket = SKAction.sequence([
SKAction.waitForDuration(0.0, withRange: 1.0),
SKAction.animateWithTextures([rocket0,
rocket1,
rocket2,
rocket3,
rocket4,
rocket5],
timePerFrame: 0.1)])
let rocketAnim = SKAction.repeatActionForever(animateRocket)
let rocket = SKSpriteNode(texture: rocket1)
rocket.runAction(rocketAnim)
rocket.setScale(0.5)
rocket.position = CGPoint(x: self.frame.size.width * 0.35, y: self.frame.size.height * 0.5)
rocket.physicsBody = SKPhysicsBody(circleOfRadius: rocket.size.height)
rocket.physicsBody?.dynamic = true
rocket.physicsBody?.allowsRotation = false
//bitmask
rocket.physicsBody?.contactTestBitMask = asteroidCategory
rocket.physicsBody?.collisionBitMask = asteroidCategory
self.addChild(rocket)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
rocket.physicsBody!.applyImpulse(CGVectorMake(0, 30))
rocket.physicsBody!.velocity = CGVectorMake(0, 300)
println(location)
//if start.containsPoint(location) {
// self.physicsWorld.gravity = CGVectorMake(0.0, -3.0)
// start.removeFromParent()
// }
}
}
}
一切都是正确定义的,只是&#34;!&#34;使比赛崩溃。
答案 0 :(得分:0)
我拿出了let rocket = SKSpriteNode(texture: rocket1)
把它放在class
下面的最顶端。我确保在项目的最顶端而不是函数内调用它。