1
votes

Whenever I run my project, I get a bad instruction error on the line...

ground.physicsBody!.dynamic = false

Here is the full code I am running to go with this snippet. I'm not sure what is happening and I don't have a lot of experience with optionals.

Code:

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

1 Answers

5
votes

You are re initialising ground after creating its physics body and hence the new object does not have physics body thus showing the nil error.

Change your code to

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)

As per the comment, general practice when you face the error of found nil when unwrapping optionals is to use either ? or a if let to safely un wrap. In this scenario it can be implemented like

if let physicsBodyObject = ground.physicsBody {
    physicsBodyObject.dynamic = false
    physicsBodyObject.allowsRotation = false
    //other code
}