user3482617
user3482617

Reputation: 307

Spritekit | Swift 3 | GameScene.sks - Physics properties only applied to one SKSpritenode

I have a GameScene.sks where I have added two SkSpritenodes both called trampoline. The code gives the trampoline object a physics body etc. but when run. Only the first trampoline has a body.

Any idea why it does not get applied to all nodes with the same name?

//Trampoline
var trampoline: SKSpriteNode?       

 override func didMove(to view: SKView) {
trampoline = childNode(withName: "trampoline") as? SKSpriteNode
            trampoline?.physicsBody = SKPhysicsBody.init(rectangleOf: (trampoline?.size)!)
            trampoline?.physicsBody?.affectedByGravity = false
            trampoline?.physicsBody?.isDynamic = false
            trampoline?.physicsBody?.usesPreciseCollisionDetection = true
            trampoline?.physicsBody?.restitution = 1
}

Upvotes: 1

Views: 178

Answers (1)

Steve Ives
Steve Ives

Reputation: 8134

childNode(withName: "trampoline") as? SKSpriteNode 

will only return a single node called trampoline which you then assign to your trampoline variable; you need to enumerate over ALL nodes called trampoline and set their physics bodies. E.g.

enumerateChildNodesWithName("trampoline") { trampolineNode, _ in
    trampolineNode?.physicsBody = SKPhysicsBody.init(rectangleOf: (trampolineNode?.size)!)
    trampolineNode?.physicsBody?.affectedByGravity = false
    trampolineNode?.physicsBody?.isDynamic = false
    trampolineNode?.physicsBody?.usesPreciseCollisionDetection = true
    trampolineNode?.physicsBody?.restitution = 1
}

Watch out for that .isDynamic property; if 'false', the body won't be involved in collisions or contacts.

Upvotes: 3

Related Questions