0
votes

I am trying to scroll game background vertically and it works for some time and later background become empty. this is what I have tried:

var background = SKSpriteNode(imageNamed: "bgPlayScene")

func addBG() {

    let backgroundTexture = SKTexture(imageNamed: "bgPlayScene")

    let shiftBackground = SKAction.moveToY(-backgroundTexture.size().height, duration: 9)
    let replaceBackground = SKAction.moveToY(backgroundTexture.size().height, duration: 0)
    let movingAndReplacingBackground = SKAction.repeatActionForever(SKAction.sequence([shiftBackground,replaceBackground]))

    for var i = 0; i<3; i++ {
        println(i)
        //defining background; giving it height and moving width
        background=SKSpriteNode(texture:backgroundTexture)
        background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
        background.size.width = self.frame.width
        background.runAction(movingAndReplacingBackground)

        self.addChild(background)
    }
}

This is what I am getting: http://gyazo.com/3da3a267aeb030225fdb8c0d563276aa I don't know what I am missing.Please let me know if there is another better way to do this.

1
You need to have two scrolling backgrounds for endless scrolling: stackoverflow.com/a/20020023/437146NightFury

1 Answers

4
votes

As suggested by iAnum I got answer from that post and here is my code:

This way I add 2 backgrounds.

func addScrollingBG() {

    bg1 = SKSpriteNode(imageNamed: "bgPlayScene")
    bg1.anchorPoint = CGPointZero
    bg1.position = CGPointMake(0, 0)
    bg1.size = CGSize(width: frame.size.width, height: frame.size.height)
    addChild(bg1)

    bg2 = SKSpriteNode(imageNamed: "bgPlayScene")
    bg2.anchorPoint = CGPointZero
    bg2.position = CGPointMake(0, bg1.size.height + 1)
    bg2.size = CGSize(width: frame.size.width, height: frame.size.height)
    self.addChild(bg2)

}

And this is my update method:

override func update(currentTime: NSTimeInterval) {

    bg1.position = CGPointMake(bg1.position.x, bg1.position.y-4)
    bg2.position = CGPointMake(bg2.position.x, bg2.position.y-4)

    if bg1.position.y < -bg1.size.height {
        bg1.position = CGPointMake(bg1.position.x, bg2.position.y + bg2.size.height)
    }
    if bg2.position.y < -bg2.size.height {
        bg2.position = CGPointMake(bg2.position.x, bg1.position.y + bg1.size.height)
    }
}