SpriteKit解包可选错误(Swift)

时间:2016-06-03 15:59:26

标签: ios swift sprite-kit optional exc-bad-instruction

每当我运行我的项目时,我都会在线路上收到错误的指令错误...

ground.physicsBody!.dynamic = false

以下是我正在使用此代码段运行的完整代码。我不确定发生了什么,我对选项有很多经验。

代码:

var ground = SKSpriteNode()
ground.position = CGPointMake(0, 0)
ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.frame.size.width, 30))
let groundTexture = SKTexture(imageNamed: "Red.png")
ground = SKSpriteNode(texture: groundTexture)
ground.physicsBody!.dynamic = false
ground.physicsBody?.allowsRotation = false

ground.physicsBody!.categoryBitMask = ColliderType.Object.rawValue
ground.physicsBody!.contactTestBitMask = ColliderType.Object.rawValue
ground.physicsBody!.collisionBitMask = ColliderType.Object.rawValue
self.addChild(ground)

1 个答案:

答案 0 :(得分:5)

在创建物理主体之后,重新初始化 ground,因此新对象没有物理主体,从而显示零错误。

将您的代码更改为

let groundTexture = SKTexture(imageNamed: "Red.png")
var ground = SKSpriteNode(texture: groundTexture)
ground.position = CGPointMake(0, 0)
ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.frame.size.width, 30))
ground.physicsBody!.dynamic = false
ground.physicsBody?.allowsRotation = false

ground.physicsBody!.categoryBitMask = ColliderType.Object.rawValue
ground.physicsBody!.contactTestBitMask = ColliderType.Object.rawValue
ground.physicsBody!.collisionBitMask = ColliderType.Object.rawValue
self.addChild(ground)

根据评论,当您在解包选项时遇到发现nil错误时的一般做法是使用?if let安全地解包。在这种情况下,它可以像

一样实现
if let physicsBodyObject = ground.physicsBody {
    physicsBodyObject.dynamic = false
    physicsBodyObject.allowsRotation = false
    //other code
}