6

im having the following issue trying to code a flappy birds clone in Xcode 6 beta 7 with Swift and SpriteKit.

After I add the physicsBody property to a SKSpriteNode I cannot change a property of physicsBody directly, for instance I cannot do the following:

bird = SKSpriteNode(texture: birdTexture1)
bird.position = CGPoint(x: self.frame.size.width / 2.8, y: CGRectGetMidY(self.frame))
bird.runAction(flight)
bird.physicsBody = SKPhysicsBody(circleOfRadius: bird.size.height/2)
bird.physicsBody.dynamic = true
bird.physicsBody.allowsRotation = false

Xcode build will fail with errors on the two lines where i add dynamic and allowsRotation values to PhysicsBody, the only way I can do it is by doing the following:

bird.physicsBody?.dynamic = true
bird.physicsBody?.allowsRotation = false

The issue of having physicsBody as optional with the '?' character is that it makes it complicated to do certain operations when trying to manipulate some bird physics I wanted to add, like rotation when moving.

Any suggestion on how to avoid / fix having to mark the physicsBody property as optional? ('physicsBody?')

Thanks!

Screenshot of issue
(source: tinygrab.com)

Zoom Screenshot of issue
(source: tinygrab.com)

Glorfindel
  • 21,988
  • 13
  • 81
  • 109

2 Answers2

2

Actually,this problem has a simple way to fix it. You can add ! after the physicsBody like this

bird.physicsBody!.dynamic = true

Reason: Inside the SKNode code,you will see this statement:

var physicsBody: SKPhysicsBody?

The physicsBody is a Nullable Type.So XCode does check to prevent you unwrap the nil value.

tsingroo
  • 189
  • 1
  • 3
1

I solve it creating a object for the SKPhysics body and assigning it to the Sprite AFTER configuring it:

let body = SKPhysicsBody(circleOfRadius: bird.size.height/2)
body.dynamic = true
body.allowsRotation = false

bird.physicsBody = body
Marioea
  • 201
  • 2
  • 5