user3886268
user3886268

Reputation: 73

How would I get my background image to repeat forever in Swift?

I have these two images that are the same image and I want them to repeat so it looks like the background is moving. I have this code but only one of the background images goes through then it goes back to the grey screen. The other background image doesn't follow the first one. How do I fix that? Thanks! (This is in swift xcode)

 func spawnBackground() {

    let cloud = SKSpriteNode(imageNamed: "CloudBg")
    let cloud2 = SKSpriteNode(imageNamed: "CloudBg2")


    cloud.position = CGPointMake(frame.size.width + cloud.frame.size.width / 2,cloud.frame.height / 2)
    cloud.setScale(1.35)
    cloud.zPosition = -15

    cloud2.position = CGPointMake(self.size.width/2, self.size.height/2)
    cloud2.setScale(1.35)
    cloud.zPosition = -15


    let moveTop = SKAction.moveByX(0, y: cloud.size.height, duration:   NSTimeInterval(CGFloat(gameSpeed) * cloud.size.height))
    cloud.runAction(SKAction.repeatActionForever(moveTop))
    cloud2.runAction(SKAction.repeatActionForever(moveTop))



    addChild(cloud)
    addChild(cloud2)


}

Upvotes: 0

Views: 717

Answers (1)

Kendel
Kendel

Reputation: 1708

I think you are looking for an action sequence like this:

  let cloud = SKSpriteNode(imageNamed: "CloudBg")
        let cloud2 = SKSpriteNode(imageNamed: "CloudBg2")


        cloud.position = CGPointMake(frame.size.width + cloud.frame.size.width / 2,cloud.frame.height / 2)
        cloud.setScale(1.35)
        cloud.zPosition = -15

        cloud2.position = CGPointMake(self.size.width/2, self.size.height/2)
        cloud2.setScale(1.35)
        cloud.zPosition = -15

        var actionone = SKAction.moveToX(0, y: cloud.size.height, duration:   NSTimeInterval(CGFloat(gameSpeed) * cloud.size.height))

        var actiontwo = SKAction.runBlock({
            cloud.position = CGPointMake(frame.size.width + cloud.frame.size.width / 2,cloud.frame.height / 2)
        })

        cloud.runAction(SKAction.repeatForever(SKAction.sequence([actionone,actiontwo])))

Of course you will have to edit this code to work where when one cloud reaches a certain point the other one begins, but that is the general idea.

Upvotes: 1

Related Questions