1

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 Answers1

5

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
}
Shubhank
  • 21,721
  • 8
  • 65
  • 83
  • 1
    Your answer is correct but I would suggest you make some slight tweaks for future readers. To avoid crashes in the first place you should replace all the ! with ? whenever possible. Not the best practice to force unwrap even though you know the physics body is there. – crashoverride777 Jun 03 '16 at 17:25
  • 1
    Or even better, just create the physics body separately, then assign it to the node when done configuring it. – Hamish Jun 03 '16 at 17:30