Swift SpriteKit PhysicsBody forced as optional by Xcode
Asked Answered
F

2

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)

Floatation answered 3/9, 2014 at 7:45 Comment(0)
H
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.

Hexangular answered 19/9, 2014 at 7:33 Comment(0)
W
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
Whiteley answered 15/9, 2014 at 15:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.