Spritekit:如何让新生的敌舰向玩家射击子弹?

时间:2016-11-07 05:17:00

标签: ios swift sprite-kit

我需要帮助,想出让新出生的敌舰全部射击子弹的方法。问题是我实际上并不知道我将如何做到这一点。我尝试使用可变计时器,但是它只射出一条直线,我无法控制它产生的位置。

Game Picture: There are more enemies spawning 我试过的:

var EnemyTimer = Foundation.Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(GameScene.spawnBullet3), userInfo: nil, repeats: true)

也试过:

 }
func spawnBullet3(){
    let Bullet = SKSpriteNode(imageNamed: "eBullet.png")
    Bullet.setScale(1)
    Bullet.zPosition = -1

    Bullet.position = CGPoint(x: enemy.position.x, y: enemy.position.y)

    let action = SKAction.moveTo(y: self.size.height + 100, duration: 0.5)
    let actionDone = SKAction.removeFromParent()
    Bullet.run(SKAction.sequence([action, actionDone]))

    Bullet.physicsBody = SKPhysicsBody(rectangleOf: Bullet.size)
    Bullet.physicsBody?.categoryBitMask = PhysicsCategories.Bullet
    Bullet.physicsBody!.collisionBitMask = PhysicsCategories.None
    Bullet.physicsBody?.contactTestBitMask = PhysicsCategories.Enemy
    Bullet.physicsBody?.affectedByGravity = true
    Bullet.physicsBody?.isDynamic = false
    self.addChild(Bullet)

}

1 个答案:

答案 0 :(得分:0)

嗯,首先,(正如LearnCocos2D奇妙地解释here 从不用户TimerperformSelector:afterDelay:或Grand Central Dispatch(GCD,即任何dispatch_...方法。

在此之前,你必须设置一些东西:

首先,替换为spawnBullet3函数添加参数(如果使用自定义类将enemy:SKSpriteNode替换为enemy:yourCustomClass

func spawnBullet3(enemy:SKSpriteNode){
   let Bullet = SKSpriteNode(imageNamed: "eBullet.png")
   Bullet.setScale(1)
   Bullet.zPosition = -1

   Bullet.position = CGPoint(x: enemy.position.x, y: enemy.position.y)

   let action = SKAction.moveTo(y: self.size.height + 100, duration: 0.5)
   let actionDone = SKAction.removeFromParent()
   Bullet.run(SKAction.sequence([action, actionDone]))

   Bullet.physicsBody = SKPhysicsBody(rectangleOf: Bullet.size)
   Bullet.physicsBody?.categoryBitMask = PhysicsCategories.Bullet
   Bullet.physicsBody!.collisionBitMask = PhysicsCategories.None
   Bullet.physicsBody?.contactTestBitMask = PhysicsCategories.Enemy
   Bullet.physicsBody?.affectedByGravity = true
   Bullet.physicsBody?.isDynamic = false
   self.addChild(Bullet)
}

其次,创建一个公共敌人数组(同样,如果你使用自定义类将SKSpriteNode替换为你的自定义类名)

var enemies:[SKSpriteNode] = []

接下来,每次创建新敌人时,将敌人附加到数组

enemies.append(newEnemy)

现在您有两个选择:

选项1:使用SKAction

使用SKAction计时器每隔几秒钟自动完成每次敌人射击(将SKAction.waitForDuration(2.5)替换为SKAction.waitForDuration(yourAmountOfSeconds)

for e in enemies
{
   var wait = SKAction.waitForDuration(2.5)
   var run = SKAction.runBlock {
      spawnBullet3(e)
   }

   e.runAction(SKAction.repeatActionForever(SKAction.sequence([wait, run])))
}

选项2:使用update功能

使用update函数中的currentTime(将currentTime.truncatingRemainder(dividingBy: 3)替换为currentTime.truncatingRemainder(dividingBy: yourAmountOfSeconds)

override func update(_ currentTime: TimeInterval) {
   [...]

   if currentTime.truncatingRemainder(dividingBy: 3) == 0
   {
      for e in enemies
      {
         spawnBullet3(e)
      }
   }
}