user3886268
user3886268

Reputation: 73

Repeating a Background Image in Swift

Im using swift programming language in xcode and in spritekit. I want to get my background image to scroll forever. I have this code so far but when I run it in the simulator it goes through only one time and goes back to the grey background. How do I get it so that the background repeats forever. I already got the background to move its just that I want it to repeat forever.

class GameScene: SKScene, SKPhysicsContactDelegate {
var background = SKSpriteNode()


         // Background

    background = SKSpriteNode(imageNamed: "background")
    background.position = CGPointMake(self.size.width/2, self.size.height/2)
    addChild(background)

    // Repeat Background Image Forever

    moveForeverAction()

    }

        //loop background image infinitely

    func moveForeverAction() {
    let moveNode = SKAction.moveByX(0, y: background.size.height * 2.0 , duration: NSTimeInterval(0.01 * background.size.height * 2.0))
    let resetPosition = SKAction.moveByX(0, y:  background.size.height * 2.0, duration: 0)
    let moveNodeForever = SKAction.repeatActionForever(SKAction.sequence([moveNode, resetPosition]))
    background.runAction(moveNodeForever)
}

Upvotes: 0

Views: 2922

Answers (2)

Philippe Coder
Philippe Coder

Reputation: 11

It's because you're adding the same background. add another declaration of bacground in the loop :

for var i:CGFloat=0; i < 3; ++i {

**background = SKSpriteNode(imageNamed: "background")**

background.position = CGPointMake(background.size.width / 2, i * background.size.height )
background.runAction(moveNodeForever)

}

Upvotes: 1

Nicola&#239; Philippe
Nicola&#239; Philippe

Reputation: 49

You've to runAction() 3 times. For example :

for var i:CGFloat=0; i < 3; ++i {

background.position = CGPointMake(background.size.width / 2, i * background.size.height )
background.runAction(moveNodeForever)

}

Upvotes: 0

Related Questions