Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
985 views
in Technique[技术] by (71.8m points)

xcode - How would I repeat an action forever in Swift?

http://i.imgur.com/xkWTk9i.png I 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.

.

 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)
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can repeat the function execution with 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.

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...