我试图在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次击中后删除敌人吗?
答案 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)
}