// Generates the pipes in FlappySwift. func generatePipes() -> SKNode { // The node that represents all of the pipes. let pipes = SKNode() // Load the textures. let pipeTextureBottom = SKTexture(imageNamed: "PipeUp") let pipeTextureTop = SKTexture(imageNamed: "PipeDown") pipeTextureBottom.filteringMode = .Nearest pipeTextureTop.filteringMode = .Nearest // Animation that moves the pipes from right to left. let distanceToMove = CGFloat( self.frame.size.width + 2.0 * pipeTextureBottom.size().width) let movePipes = SKAction.moveByX( -distanceToMove, y:0.0, duration: NSTimeInterval(0.01 * distanceToMove)) // Animation the removes pipes. let removePipes = SKAction.removeFromParent() // Put them together. let movePipesAndRemove = SKAction.sequence([movePipes, removePipes]) // Animation which spawns the pipes at a random height. // But always makes the pipes 150 pixels away from each other. let spawn = SKAction.runBlock({ () -> Void in let pipePair = SKNode() pipePair.position = CGPointMake( self.frame.size.width + pipeTextureBottom.size().width * 2, 0) let maxHeight = UInt32(self.frame.size.height / 6) let bottomHeight = arc4random() % maxHeight + maxHeight // Set up the bottom pipe. let bottomPipe = SKSpriteNode(texture: pipeTextureBottom) bottomPipe.setScale(2.5) bottomPipe.position = CGPointMake(0.0, CGFloat(bottomHeight)) bottomPipe.physicsBody = SKPhysicsBody( rectangleOfSize: bottomPipe.size) bottomPipe.physicsBody?.dynamic = false // Set up the top pipe. let topPipe = SKSpriteNode(texture: pipeTextureTop) topPipe.setScale(2.5) topPipe.position = CGPointMake( 0.0, CGFloat(bottomHeight) + topPipe.size.height + 150.0) topPipe.physicsBody = SKPhysicsBody(rectangleOfSize: topPipe.size) topPipe.physicsBody?.dynamic = false // Add them together into the pipe pair. pipePair.addChild(bottomPipe) pipePair.addChild(topPipe) // Animate the pair. pipePair.runAction(movePipesAndRemove) // Add to our pipes. pipes.addChild(pipePair) }) // Pause. let delay = SKAction.waitForDuration(NSTimeInterval(2.0)) // Put the spawn and the delay together. let spawnThenDelay = SKAction.sequence([spawn, delay]) self.runAction(SKAction.repeatActionForever(spawnThenDelay)) return pipes }