The best way to remove the didFinishUpdate nodes is to use the didFinishUpdate method, if you delete or run the method to remove your node from didBeginContact , your game may crash in finding the oncoming node, which is in the process of removal in the meantime.
class BadGuy: SKSpriteNode { var badGuyBulletCollisionsCounter: Int = 0 init() { let texture = SKTexture(imageNamed: "CircleBadGuy") super.init(texture: texture, color: nil, size: texture.size()) ...
Declare a global var:
var nodesToRemove = [SKNode]()
In the didBeginContact method:
func didBeginContact(contact: SKPhysicsContact) { let A : SKPhysicsBody = contact.bodyA let B : SKPhysicsBody = contact.bodyB if (A.categoryBitMask == Numbering.Badguy) && (B.categoryBitMask == Numbering.Laser) || (A.categoryBitMask == Numbering.Laser) && (B.categoryBitMask == Numbering.Badguy) { badGuy = A.node as! BadGuy badGuy.badGuyBulletCollisionsCounter += 1 runAction(BadGuyLostSound) bulletsTouchedBadGuy(badGuy, Laser: B.node as! SKSpriteNode) } }
In the bulletsTouchedBadGuy method:
func bulletsTouchedBadGuy(badGuy: BadGuy, laser: SKSpriteNode){ nodesToRemove.append(laser) if badGuy.badGuyBulletCollisionsCounter == 2 { nodesToRemove.append(badGuy) } }
Finally:
override func didFinishUpdate() { nodesToRemove.forEach(){$0.removeFromParent()} nodesToRemove = [SKNode]() }
source share