Swift 如何在多次命中节点时移除节点

Swift 如何在多次命中节点时移除节点,swift,sprite-kit,Swift,Sprite Kit,我正在制作一个太空入侵者游戏,游戏中有许多敌舰向你靠近,你必须向它们射击 当玩家触摸屏幕时,玩家飞船向敌舰发射子弹 我得到了它,所以每当一颗子弹击中敌舰时,它就会从母船上移除。但我无法得到它,因此需要2颗子弹才能将敌舰从母船上移开。由于某种原因,当另一艘敌舰被召唤到现场时,敌人的生命将自行重置。我怎样才能使每艘敌舰都有自己的独立生命,并且不会影响其他敌舰的生命 这是敌人的等级: public class Villain: SKSpriteNode { var life = 2 init(){

我正在制作一个太空入侵者游戏,游戏中有许多敌舰向你靠近,你必须向它们射击

当玩家触摸屏幕时,玩家飞船向敌舰发射子弹

我得到了它,所以每当一颗子弹击中敌舰时,它就会从母船上移除。但我无法得到它,因此需要2颗子弹才能将敌舰从母船上移开。由于某种原因,当另一艘敌舰被召唤到现场时,敌人的生命将自行重置。我怎样才能使每艘敌舰都有自己的独立生命,并且不会影响其他敌舰的生命

这是敌人的等级:

public class Villain: SKSpriteNode {

var life = 2

init(){

    let texture = SKTexture(imageNamed: "Villain")
    var life = 2
    print("number of lives: ", life)
    super.init(texture: texture, color: SKColor.clear, size: texture.size())
    self.name = "villain"
}

required public init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
这是游戏场景类,其中敌人类被称为

func VillainRight(){
    let TooMuch = self.size.width
    let point = UInt32(TooMuch)

    let VillainR = Villain()

    VillainR.zPosition = 2
    VillainR.position = CGPoint(x: self.frame.minX,y: CGFloat(arc4random_uniform(point)))

    //This code makes the villain's Zposition point towards the SpaceShip
    let angle = atan2(SpaceShip.position.y - VillainR.position.y, SpaceShip.position.x - VillainR.position.x)
    VillainR.zRotation = angle - CGFloat(M_PI_2)

    let MoveToCenter = SKAction.move(to: CGPoint(x: self.frame.midX, y: self.frame.midY), duration: 15)

    //Physics World
    VillainR.physicsBody = SKPhysicsBody(rectangleOf: VillainR.size)
    VillainR.physicsBody?.categoryBitMask = NumberingPhysics.RightV
    VillainR.physicsBody?.contactTestBitMask = NumberingPhysics.Laser | NumberingPhysics.SpaceShip
    VillainR.physicsBody?.affectedByGravity = false
    VillainR.physicsBody?.isDynamic = true

    VillainR.run(MoveToCenter)
    addChild(VillainR)
}
下面是didBeginContact方法的一部分:

 //LASERS HIT ENEMY CHECK

    if BodyOne.categoryBitMask == NumberingPhysics.Laser && BodyTwo.categoryBitMask == NumberingPhysics.LeftV{
        run(VillainGone)
        ToNextLevel -= 1

        if BodyTwo.node != nil{
            MakeExplosions(BodyTwo.node!.position)
        }

        BodyTwo.node?.removeFromParent()
        BodyOne.node?.removeFromParent()
    }

    if BodyOne.categoryBitMask == NumberingPhysics.Laser && BodyTwo.categoryBitMask == NumberingPhysics.RightV{

        ToNextLevel -= 1

        if BodyTwo.node != nil{
            MakeExplosions(BodyTwo.node!.position)
        }

        run(VillainGone)
        BodyOne.node?.removeFromParent()
        BodyTwo.node?.removeFromParent()
    }
}
概述:


我所要做的就是一旦有两颗子弹击中敌舰,就把它从母船上移开。而且敌人的生命是相互独立的(如果一艘敌舰只剩下1条生命,那么如果另一艘敌舰被召唤到现场,它将不会重置回2条生命)。

这里是一个解决您问题的示例(这是一个macOS项目,如果您想转换,只需将
mouseDown
替换为
touchsbegind

单击屏幕以观看恶棍生命耗尽,当达到0时恶棍将死亡并从场景中移除:

let category1 = UInt32(1)
let category2 = UInt32(2)


class Villain: SKSpriteNode {

  var lives = 2
  var hitThisFrame = false

  init(color: SKColor, size: CGSize) {
    super.init(texture: nil, color: color, size: size)
    let pb = SKPhysicsBody(rectangleOf: self.size)
    pb.categoryBitMask = category1
    pb.contactTestBitMask = category2
    self.physicsBody = pb
  }

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

class Hero: SKSpriteNode {

  init(color: SKColor, size: CGSize) {
    super.init(texture: nil, color: color, size: size)
    let pb = SKPhysicsBody(rectangleOf: self.size)
    pb.categoryBitMask = category2
    pb.contactTestBitMask = category1
    self.physicsBody = pb
  }
  required init?(coder aDecoder: NSCoder) { fatalError() }
}


class GameScene: SKScene, SKPhysicsContactDelegate {

  let villain = Villain(color: .blue,  size: CGSize(width: 50, height: 50))
  let hero    = Hero   (color: .green, size: CGSize(width: 50, height: 50))

  override func didMove(to view: SKView) {
    physicsWorld.contactDelegate = self
    physicsWorld.gravity = CGVector.zero

    hero.position.y -= 100
    addChild(villain)
    addChild(hero)
  }

  func didBegin(_ contact: SKPhysicsContact) {
    let contactedBodies = contact.bodyA.categoryBitMask + contact.bodyB.categoryBitMask

    if contactedBodies == category1 + category2 {

      // Find which one of our contacted nodes is a villain:
      var vil: Villain
      if let foundVil = contact.bodyA.node as? Villain {
        vil = foundVil
      } else if let foundVil = contact.bodyB.node as? Villain {
        vil = foundVil
      } else {
        fatalError("one of the two nodes must be a villain!!")
      }


      if vil.hitThisFrame {
        // Ignore a second contact if already hit this frame:
        return
      } else {
        // Damage villain:
        vil.lives -= 1
        print(" vil lives: \(vil.lives)")
        vil.hitThisFrame = true
        if vil.lives == 0 {
          // Kill villain:
          print("villain is dead!!!")
          vil.physicsBody = nil
          vil.removeFromParent()
        }
      }
    }
  }

  override func didSimulatePhysics() {
    // Reset hero position (so as to not trigger another didBegin()
    hero.position = CGPoint(x: 0, y: -100)
    // Allow villain to be hit again next frame:
    villain.hitThisFrame = false
  }
  override func mouseDown(with event: NSEvent) {
    // Trigger didBegin():
    hero.position = villain.position
  }
}

正如我经常建议的那样,通过每个节点的用户数据和点击次数为每个节点指定一个唯一的iD。如果我调用一个函数多次添加该节点,你能告诉我怎么做吗。是什么阻止了你运行搜索并为自己找到答案?我已经尝试过了,但找不到任何东西。我正在尝试解密你的代码,但是我很困惑,因为类型/类/结构应该写得“像这样”,方法/函数/变量/let应该写得“像这样”。如果你能更新它,它会帮我很多=)你好,这是工作有时。我有时会收到致命的错误消息“两个节点中的一个必须是恶棍!!”你能告诉我为什么会弹出此消息吗?我的代码中有一个bug。让我现在就修。它应该是固定的——我忘了引用
bodyB.NODE
,而只是使用了
bodyB
。这就是为什么我喜欢
fatalError()
,因为当你犯错误时,它会告诉你自己:)@AlexMerlinAwesome它有效!!非常感谢您长期以来帮助我解决这个问题:)@fluity@AlexMerlin np,别忘了点击复选标记“标记为已回答”,这样其他人就会知道这是有效的:)流动性,哥们儿