某些命中后如何删除敌人?

时间:2017-02-19 01:47:04

标签: sprite-kit swift3

我试图在2次射击后删除敌人。这是我的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()
        }

这会在被击中后删除敌人,有人可以告诉我如何在2次击中后删除敌人吗?

1 个答案:

答案 0 :(得分:5)

通常,尝试将节点移除到didBegin(_ contact:这不是一个好主意,因为在第一次接触后,您可能会有多个与节点成为零的联系人,这可能会导致崩溃。

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]()
}

如果您有1个敌人,此示例非常有用。 如果您有更多敌人,您可以为您的敌人类创建bulletCounter属性,或在bulletCounter SKNode属性中存储userData值:

首先创建字典:

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

在游戏中获取/分配您的价值:

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