I have a custom SKNode subclass, I want to add a child node with a physics body attached to it. I provide various ways of initializing my custom SKNode so I placed all the code that is shared by all initializers in one function onInit() it looks a bit like this:
func onInit() {
let physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 100, height: 100))
physicsBody.affectedByGravity = false
let child = SKSpriteNode(color: NSColor.grayColor(), size: CGSize(width: 100, height: 100))
child.position.y = 50
child.physicsBody = physicsBody
self.addChild(child)
}
It creates a child node with a physics body attached to it. So I call this function from two initializers: init() and init(coder aDecoder: NSCoder) (after calling super.init of course)
the thing is I noticed when I place a node with my custom class in the GameScene.sks file the physics body isn't created. I know the node is initialized as my custom class because the child sprite node does get created (I can see it), but it just is created without a physics body attached to it.
If I add the node programatically using any other initalizer the child node does have a physics body.
Please note I don't want to add the physics body on my custom node itself (subclass of SKNode), but in a child of that node (though it doesn't work on the custom node either). Here is how I call onInit inside the initializers:
init() {
... //Do some initialization
super.init()
self.onInit()
}
required init?(coder aDecoder: NSCoder) {
...//Some more initialization
super.init(coder: aDecoder)
self.onInit()
}
So the question is why is this happening, is it a bug (it looks like on to me), and is there something else I can do?
UPDATE
I later found out the node still has a reference to the physics body I created (calling myNode.physicsBody doesn't return nil), it is just not participating on the physics simulation
Also I found this other question describing a pretty similar issue