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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26915390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:10:22  来源:igfitidea点击:

How would I repeat an action forever in Swift?

xcodeswift

提问by user3886268

http://i.imgur.com/xkWTk9i.pngI already got this rectangle to go from top to bottom. The problem I have is that I want it to repeat every 2 seconds so another rectangle is following it. I want my code to spawn the rectangles every 2 seconds and have it repeat like in flappy bird does with the green pipes. Thank you. (I got this to work before but I deleted my project by mistake and cant figure out how I did it in the first place.) Im in Swift using Spritekit.

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

.

.

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

回答by Dharmesh Kheni

You can repeat the function execution with NSTimer.

您可以使用 重复执行函数NSTimer

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

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

   }

This will repeat your function execution for every 2 second.

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

EDIT :

编辑 :

You can do it this way too :

你也可以这样做:

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

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

}

回答by Aaron Halvorsen

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