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!
(source: tinygrab.com)
(source: tinygrab.com)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With