我如何在Swift中永远重复一个动作?

时间:2014-11-13 17:59:13

标签: xcode swift

http://i.imgur.com/xkWTk9i.png我已经让这个矩形从上到下。我遇到的问题是我希望它每2秒重复一次,所以另一个矩形跟随它。我希望我的代码每隔2秒生成一个矩形,然后让它重复,就像绿色的管道一样。谢谢。 (我之前已经开始工作,但我错误地删除了我的项目,并且无法弄清楚我是如何做到的。)我在Swift中使用Spritekit。

 class GameScene: SKScene {
   let sprite = SKSpriteNode(imageNamed: "Rectangle 12")

   override func didMoveToView(view: SKView) {
     self.addChild(sprite)

      //run doAction function
      doAction()

   }


   //movement of rectangle


  func createRectangle() {
    let moveToBottom = SKAction.moveByX(0, y: 0 - self.frame.size.width , duration:  
    NSTimeInterval (3.0))

    let removeTheNode = SKAction.removeFromParent()
    let moveAndRemovePipes = SKAction.sequence([moveToBottom, removeTheNode])
    let repeatAction = SKAction.repeatActionForever(moveAndRemovePipes)
    sprite.xScale = 1
    sprite.yScale = 1
    sprite.position = CGPoint(x:0,y:0)
    sprite.runAction(repeatAction)


  }
  //spawn multiple rectangles after 3 or 4 seconds

  func doAction() {
    let generateRectangles = SKAction.sequence([
    SKAction.runBlock(self.createRectangle),
    SKAction.waitForDuration(NSTimeInterval(3.0))])
    let endlessAction = SKAction.repeatActionForever(generateRectangles)
    runAction(endlessAction)
  }
}

2 个答案:

答案 0 :(得分:10)

您可以使用NSTimer重复执行功能。

override func didMoveToView(view: SKView) {
     self.addChild(sprite)

       var timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "doAction", userInfo: nil, repeats: true)

   }

这将每2秒重复执行一次函数。

编辑:

你也可以这样做:

override func didMoveToView(view: SKView) {
 self.addChild(sprite)

 runAction(SKAction.repeatActionForever(SKAction.sequence([SKAction.runBlock(doAction), SKAction.waitForDuration(1.0)])))

}

答案 1 :(得分:1)

run(SKAction.repeatForever(SKAction.sequence([SKAction.run(doAction), SKAction.wait(forDuration: 2.0)])))