Reputation: 615
I'd really like to debug some of my in game physics in a playground where it's a bit easier to see what's going on and run some test code. I've simplified my problem down to a small snippet that you can copy and paste into a playground to see if you can reproduce this problem and perhaps provide a solution:
import SpriteKit
import PlaygroundSupport
let sceneView = SKView(frame: CGRect(x: 0, y: 0, width: 480,
height: 320))
let scene = SKScene(size: CGSize(width: 480, height: 320))
sceneView.showsFPS = true
sceneView.showsPhysics = true
sceneView.presentScene(scene)
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = sceneView
let test = SKShapeNode(rectOf: CGSize(width:100,height:100))
test.fillColor = UIColor.red
test.position = CGPoint(x:scene.size.width/2, y: scene.size.height/2)
test.zPosition = 1
test.physicsBody? = SKPhysicsBody(circleOfRadius: 50)
scene.addChild(test)
You should see a square at the center of your playground output.
The problem is that the SKPhysicsBody call to create a circle physics body seems to be returning nil. If I remove the optional notation:
test.physicsBody = .....
The call fails and the node fails to appear in the scene.
Anybody know what I'm lacking in my playground setup or in the code to allow me to create and see physics bodies? Ideally I'd like to add several of my more complex characters and then tweak the physics bodies, joints etc in the playground where I can observe them easily before adding the modifications back into the game.
Upvotes: 0
Views: 125
Reputation: 8134
Remove the ? from:
test.physicsBody? =
What's happening is that Swift is looking to see if test.physicsBody
exists because it's an optional and the '?' and finds that it doesn't, so doesn't bother with the rest of the line (the = SKPhysicsBody(circleOfRadius: 50)
)
You can verify this with the follwong code in a playground:
var myOpt: Int?
myOpt? = 4
print((myOpt) // Prints nil.
myOpt = 5
print(myOpt) // Prints Otional(5)
Tip - when dealing with optionals, I read my code to myself using a questioning tone of voice when I see an '?' and a forceful tone of voice when I see a '!', which helps me remember that ? means 'Does this exist?' and ! means 'JUST DO IT!'
Edit - just seen that you did try without the '?', but you said that "The call fails and the node fails to appear in the scene.".
I just tried your code in a Playground and it works fine. The square appears before disappearing as it plummets endlessly downwards under the effect of gravity. :-)
Add:
scene.physicsWorld.gravity = CGVector(dx:0, dy:0)
before you do your addChild
Upvotes: 2