Nimbahus
Nimbahus

Reputation: 487

Sprite Kit Background scroll vertical

I want to create a scrolling Background that moves vertically. Since I want to stop the Background whenever I want, I don't want it to be implemented in the Update: Function.

Within my code, the Background scrolls vertically, but still not perfect. Sometimes it randomly pop ups, or let the whole scene down to lower FPS.

Update 1:

Like Christian said, I used now the the Update Function, but with a Bool to determine if it should stop or not. As you can see I speed up the Scene, but the speed of the Background move will not change. How can I faster up the Background?

Code :

  ...
  var Scroll:Bool!
  ...
  self.runAction(SKAction.speedBy(2.0, duration: 25))
  ...

  func addBackground(){

    Background1 = SKSpriteNode(imageNamed: "Background.png")
    Background1.size = CGSize(width: self.frame.size.width, height: self.frame.size.height)
    Background1.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
    Background1.zPosition = 1
    self.addChild(Background1)

    Background2 = SKSpriteNode(imageNamed: "Background.png")
    Background2.size = CGSize(width: self.frame.size.width, height: self.frame.size.height)
    Background2.position = CGPoint(x: self.frame.size.width / 2, y: Background1.position.y - Background2.size.height)
    Background2.zPosition = 1
    self.addChild(Background2)

}

override func update(currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */

    if (Scroll == true){

    Background1.position = CGPointMake(Background1.position.x, Background1.position.y + 4)
    Background2.position = CGPointMake(Background2.position.x, Background2.position.y + 4)

    if(Background1.position.y > self.frame.size.height + (Background1.size.height / 2))
    {
        Background1.position = CGPointMake(self.frame.size.width / 2, Background2.position.y - Background1.size.height)
    }

    if(Background2.position.y > self.frame.size.height + (Background2.size.height / 2))
    {
        Background2.position = CGPointMake(self.frame.size.width / 2, Background1.position.y - Background2.size.height)

    }

    }
}

Upvotes: 1

Views: 325

Answers (1)

Christian
Christian

Reputation: 22343

You should put it inside the update method. You could use a boolean to stop the updating-process. for example:

var moveBackground = true

func stopBackgroundMovement(){
    moveBackground = false
}

//In your update-method:
if moveBackground {
    //move the background
    Background.position.y += 1
}

If you want to call the update function every x seconds, you can use the NSTimeInterval parameter from the update method.

Upvotes: 4

Related Questions