1

First I defined a class named AlienNode which inherit from SKSpriteNode, here's the class

var hP = 0

init() {
    self.hp = 5
    var alienTexture = SKTexture(imageNamed: "Alien_Normal.png")
    super.init(texture: alienTexture, color: UIColor.white, size: alienTexture.size())
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

in GameScene, I shoot a bullet to the alien, and detect its collision, in the function didBegin()

    let nodesName = [contact.bodyA.node?.name,contact.bodyB.node?.name]
    print(nodesName)

    if nodesName.contains(kAlienName) && nodesName.contains(kBulletName) {
        //A bullet hit a alien
        run(SKAction.playSoundFileNamed("Scream.wav", waitForCompletion: false))

        var alienNode: AlienNode
        if let _ = contact.bodyA.node as? AlienNode {
            contact.bodyB.node?.removeFromParent() //Remove the bullet
            alienNode = contact.bodyA.node as! AlienNode
        }
        else {
            contact.bodyA.node?.removeFromParent() //Remove the bullet
            alienNode = contact.bodyB.node as! AlienNode
        }

        alienNode.hP -= 1
        print("hit")
        if alienNode.hP <= 0 {
            alienNode.removeFromParent()
            print("Alien killed")
        }

the result is, sometimes it detect one collision, sometimes two, which make me confused, how could I fix that?

Shamim Hossain
  • 1,690
  • 12
  • 21
Ethan Chu
  • 77
  • 4
  • Possible duplicate of [Why are didBeginContact called multiple times?](https://stackoverflow.com/questions/24228274/why-are-didbegincontact-called-multiple-times) – Knight0fDragon Jul 08 '18 at 04:38
  • See my answer on here https://stackoverflow.com/questions/24228274/why-are-didbegincontact-called-multiple-times/38364703 – Knight0fDragon Jul 08 '18 at 04:38
  • You can’t “fix it” - If 2 nodes touch in 2 different places, ‘didBegin‘ gets called twice in a single ‘uodate’ loops.. what you have to do is to handle it e.g. set a flag in your contact code and if the flag is set, do nothing, or if you are removing nodes add the node to a set of nodes to be removed and remove them later, or if you remove them, check if the node is nil etc. There are lots of answers to lots of questions about ‘multiple contacts’ – Steve Ives Jul 08 '18 at 16:08

0 Answers0