Sprite Kit Could not create physics body error

Whats my problem: I get the Could not create physics body error when call the constructor SKPhysicsBody(texture: size:)

I am creating the physics body for my custom SKSpriteNode object in the required init(coder aDecoder: NSCoder) constructor, so I can design my game easily in the scene editor. I need the physics body to be created according to the texture I set to in the scene editor. Here is the code I have so far:

    import Foundation     import SpriteKit      class Attachable : SKSpriteNode {         init(texture: SKTexture, position: CGPoint, size: CGSize ) {         super.init(texture: texture , color: UIColor.clear, size: size)         self.position = position              }         required init(coder aDecoder: NSCoder) {             super.init(coder: aDecoder)!             DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) {                              self.physicsBody = SKPhysicsBody(texture: (self.scene?.view?.texture(from:              SKSpriteNode(texture: self.texture)))!, size: self.size)                      let joint = SKPhysicsJointFixed.joint(withBodyA: self.physicsBody!, bodyB: (.              self.parent?.physicsBody)!, anchor: self.parent!.position)             self.scene!.physicsWorld.add(joint)             }              }         } 

As your can see the call ‘texture: (self.scene?.view?.texture(from: SKSpriteNode(texture:self.texture)))!’ is a supposed workaround I saw from another post with this same bug but it isn’t working, probably from the latest update with xcode. The deserialization initializer assumes I’ve chose a texture in the scene editor for the Attachable object. Also Im doing the async thing because the joint needs to be created after one of the bodies is initialized. I will come up with a more elegant solution but thats outside the scope of this question.

Edit: I can set the alpha physicsbody in the scene editor, so thats a work around but I’d prefer to create the body in the class.

Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.