sicvayne
sicvayne

Reputation: 620

How to delete enemy after certain hits?

I am trying to delete an enemy after 2 shots.Here is my didBegin

func didBegin(_ contact: SKPhysicsContact) {

    var body1:SKPhysicsBody
    var body2:SKPhysicsBody

    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
        body1 = contact.bodyA
        body2 = contact.bodyB
    }else{
        body1 = contact.bodyB
        body2 = contact.bodyA
    }


    if body1.categoryBitMask == PhysicsCatagory.Bullet && body2.categoryBitMask == PhysicsCatagory.Enemy{
        //if the bullet has hit the enemy
        if body2.node != nil {
            spawnSplatter(spawnPosition: body2.node!.position)
            body1.node?.removeFromParent()
            body2.node?.removeFromParent()
        }

This deletes an enemy after being hit once, can someone tell me how I can delete an enemy after 2 hits?

Upvotes: 2

Views: 115

Answers (1)

Alessandro Ornano
Alessandro Ornano

Reputation: 35402

Usually, try to remove nodes to didBegin(_ contact: it's not a good idea because you could have multiple contacts with nodes that become nil after the first contact and this could cause a crash.

var bulletCounter : Int = 0
var nodesToRemove = [SKNode]()

func didBegin(_ contact: SKPhysicsContact) {
    var body1:SKPhysicsBody
    var body2:SKPhysicsBody
    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
        body1 = contact.bodyA
        body2 = contact.bodyB
    }else{
        body1 = contact.bodyB
        body2 = contact.bodyA
    }
    if body1.categoryBitMask == PhysicsCatagory.Bullet && body2.categoryBitMask == PhysicsCatagory.Enemy{
        //if the bullet has hit the enemy
        bulletCounter += 1
        nodesToRemove.append(body1.node!) // remove always the bullet
        switch bulletCounter {
        case 2: 
           nodesToRemove.append(body2.node!) // remove enemy
           bulletCounter = 0
        default:break 
        }
    }
}
override func didFinishUpdate()
{
    nodesToRemove.forEach(){$0.removeFromParent()}
    nodesToRemove = [SKNode]()
}

This example can be useful if you have 1 enemy. If you have more enemies you can create a bulletCounter property to your Enemy class or store a bulletCounter value inside the SKNode userData property:

Create the dictionary first:

enemy.userData = NSMutableDictionary()
enemy.userData?.setObject(0, forKey: "bulletCounter")

Get/assign your value during the game:

if let bulletCounter = self.userData?.object(forKey: "bulletCounter") {
   var counter = bulletCounter as! Int
   counter += 1
   self.userData?.setObject(counter, forKey: "bulletCounter" as NSCopying)
}

Upvotes: 5

Related Questions