寻找一种每隔30秒在屏幕中心生成一个新精灵的方法。它必须受到重力的影响。
我已设法生成精灵,但在尝试将affectedByGravity设置为true时,游戏崩溃了。
"致命错误:在展开可选值时意外发现nil"
这是我得到的代码:
self.timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "spawningCars", userInfo: nil, repeats: true)
func spawningCars() {
let enemyTowardsTexture = SKTexture(imageNamed: "player")
let enemyTowards = SKSpriteNode(texture: enemyTowardsTexture)
enemyTowards.position = ourCamera.position
enemyTowards.physicsBody!.affectedByGravity = true
self.addChild(enemyTowards)
print("spawning car right")
timer.invalidate()
resetTimer()
}
func resetTimer() {
self.timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "spawningCars", userInfo: nil, repeats: true)
}
答案 0 :(得分:2)
你需要在调用sprite之前为它创建一个物理体:
enemyTowards.physicsBody = SKPhysicsBody(texture: enemyTowardsTexture, size: enemyTowardsTexture.size())