Lenny1357
Lenny1357

Reputation: 778

Strange behaviour of SKPhysicsBody

In my app I want to create a physics body for a node programmatically. However when I create the physics body programmatically, it doesn't seem to work, although the physics body created in the SpriteKit editor does work. When the physicsbody is created programmatically, it does not collide with another node, when it is created in the editor, it does.

Here is my code:

physicsBody = SKPhysicsBody(rectangleOf: size)

    if let body = self.physicsBody{
        body.isDynamic = true
        body.affectedByGravity = false
        body.allowsRotation = false
        body.categoryBitMask = CollisionCategoryBitmask.shootWall.rawValue
        body.collisionBitMask = CollisionCategoryBitmask.circle.rawValue
        body.contactTestBitMask = CollisionCategoryBitmask.circle.rawValue
    }

size is the size property of the node.

When I now comment out the first line where the physics body is assigned to the node and instead set the physics body in the SpriteKit scene editor it does work. Note that the code inside the if condition is being executed in both cases.

enter image description here

Update:

What is interesting is that when I do this:

physicsBody = SKPhysicsBody(bodies: [physicsBody!])

which shouldn't have any impact because it its basically changing nothing, then it doesn't work as well. Is this a bug in SpriteKit?

Upvotes: 1

Views: 56

Answers (1)

Knight0fDragon
Knight0fDragon

Reputation: 16837

When you do this

required init?(coder aDecoder: NSCoder) {
    factor = 0.5
    super.init(coder: aDecoder)
    self.pBody() 

}

physicsWorld does not exist yet, so the body does not get placed in the world.

You want to do it after it is created, so throw your code into a closure to be launched after your setup completes. You can do this using DispatchQueue

required init?(coder aDecoder: NSCoder) {
    factor = 0.5
    super.init(coder: aDecoder)
    DispatchQueue.main.async {
        self.pBody() //This will fire after the SKS finished building the scene, so physicsWorld will exist
    }
}

Upvotes: 3

Related Questions