So currently I am trying to make an app where when the player collides with the enemy, the enemy disappears. I have achieved this by writing this code;
func didBegin(_ contact: SKPhysicsContact) {
var firstBody = SKPhysicsBody()
var secondBody = SKPhysicsBody()
if contact.bodyA.node?.name == "Player" {
firstBody = contact.bodyA
secondBody = contact.bodyB
}else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if firstBody.node?.name == "Player" && secondBody.node?.name == "Enemy" {
}
if contact.bodyA.categoryBitMask == 1 && contact.bodyB.categoryBitMask == 2 {
self.enumerateChildNodes(withName: "Enemy") { (node:SKNode, nil) in
if node.position.y < 550 || node.position.y > self.size.height + 550 {
node.removeFromParent()
}
}
}
}
However, because I’m enumeratingChildNodes with the name "Enemy", every enemy disappears on screen. I only want the one I hit to disappear. Any help? Thanks!
2
Answers
You’ll want to replace this:
With something like this:
Contact bodyA and bodyB are the 2 nodes which have made contact with each other. The IF statement just checks to see which one is the enemy, then removes it.
JohnL has posted the correct answer, but you might find it helpful to structure your
didBegin
like this:(The print statements are for debugging and can be removed)
This code doesn’t bother assigning the bodies in the collision until required and logically ANDs the 2 category bit masks in order to ascertain what has hit what, and then using the ‘switch’ to process each collision. You could add extra switch cases for other collisions. We then use the ternary operator to get the ‘enemy’ node (Functionally the same as JohnL’s ‘if…then…) and remove it.