Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift SpriteKit PhysicsBody forced as optional by Xcode

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)

like image 574
Adrian E. Labastida Cañizares Avatar asked Sep 03 '14 07:09

Adrian E. Labastida Cañizares


2 Answers

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.

like image 103
tsingroo Avatar answered Sep 22 '22 04:09

tsingroo


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
like image 30
Marioea Avatar answered Sep 24 '22 04:09

Marioea