Swift SpriteKit PhysicsBody is forced, as an option, using Xcode

I had the following problem when I tried to encode a clone of unstable birds in Xcode 6 beta 7 using Swift and SpriteKit.

After I added a physics property to SKSpriteNode, I cannot change the physics property directly, for example, 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 

The Xcode assembly fails with errors in two lines, where I add dynamic and allows Rotation values โ€‹โ€‹in PhysicsBody, the only way I can do this is to do the following:

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

The question is that body physics is optional with '?' Typically, this complicates the performance of certain operations when trying to manipulate the physics of birds, which I wanted to add, for example, rotation during movement.

Any suggestion on how to avoid / fix the need to flag the PhysicsBody property as optional? ('PhysicsBody?)

Thanks!

Screenshot of issue
(source: tinygrab.com )

Zoom Screenshot of issue
(source: tinygrab.com )

+6
source share
2 answers

In fact, this problem has an easy way to fix it. You can add! after physics looks like this

 bird.physicsBody!.dynamic = true 

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

 var physicsBody: SKPhysicsBody? 

PhysicalBody - This is a Nullable Type.So Xcode verifies that you do not expand the nil value.

+2
source

I solve it by creating an object for the SKPhysics body and assigning it to Sprite AFTER, setting it up:

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

Source: https://habr.com/ru/post/1201707/


All Articles