Reputation: 323
I have a shooter app that is crashing when the bullet hits two overlapping nodes. I've tried everything, I tried checking if the bodies were nil but it wouldnt allow me, I'm not sure how to make this work anymore. here's the code:
func didBeginContact(contact: SKPhysicsContact) {
var firstBody:SKPhysicsBody
var secondBody:SKPhysicsBody
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask) {
firstBody = contact.bodyA
secondBody = contact.bodyB
}
else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if ((firstBody.categoryBitMask & photonCategory) != 0 && (secondBody.categoryBitMask & alientCategory) != 0){
aliensCollideWithBullets(firstBody.node as! SKSpriteNode, alien: secondBody.node as! SKSpriteNode)
// firstBody.node?.removeFromParent()
// secondBody.node?.removeFromParent()
}
}
func aliensCollideWithBullets(torpedo:SKSpriteNode, alien:SKSpriteNode) {
print("hit")
torpedo.removeFromParent()
alien.removeFromParent()
aliensDestroyed++
trumpsDestroyedLabel.text = "\(aliensDestroyed) Trumps"
if (aliensDestroyed > 10) {
}
}
the line crashing is:
if ((firstBody.categoryBitMask & photonCategory) != 0 && (secondBody.categoryBitMask & alientCategory) != 0){
aliensCollideWithBullets(firstBody.node as! SKSpriteNode, alien: secondBody.node as! SKSpriteNode)
// firstBody.node?.removeFromParent()
// secondBody.node?.removeFromParent()
}
Any help is appreciated.
Upvotes: 1
Views: 53
Reputation: 5451
Check bodyA and bodyB for nil. I had the same issue and solved it with this line of code:
if contact.bodyA.node != nil && contact.bodyB.node != nil
Upvotes: 1