Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Endless scrolling (repeating) background in Spritekit game - Swift

I want to Create a endless scrolling background for my spritekit game, iT should consist of one or two images probably, which repeat themselves? I found these one and two examples, but they are in obj. C.

I have no idea how I can achieve this in Swift. And is it possible to set the speed manually?

Ps: I don't have the skill to convert obj. C into swift (newbie to Xcode dev.)

like image 581
Egghead Avatar asked Oct 13 '14 19:10

Egghead


2 Answers

I know this is late to the game, but I found how to do this horizontally as well!

Starting off with Egghead's code (Excellent work!) I modified some things:

    let background1 = SKSpriteNode(imageNamed: "Street_Example")
    let background2 = SKSpriteNode(imageNamed: "Street_Example")

Also:

    background1.position = CGPoint(x: frame.size.width / 2, y:frame.size.height / 2)
    background1.size = CGSize(width: frame.width, height: frame.height)
    background1.anchorPoint = CGPointZero
    background1.position = CGPointMake(0, 0)
    background1.zPosition = -15
    self.addChild(background1)

    background2.size = CGSize(width: frame.width, height: frame.height)
    background2.anchorPoint = CGPointZero
    background2.position = CGPointMake(background1.size.width - 1,0)
    background2.zPosition = -15
    self.addChild(background2)

And to update the position of the background:

    background1.position = CGPointMake(background1.position.x-2, background1.position.y)
    background2.position = CGPointMake(background2.position.x-2, background2.position.y)
    if(background1.position.x < -background1.size.width)
    {
      background1.position = CGPointMake(background1.position.x + background2.size.width , background2.position.y)
    }
    if(background2.position.x < -background2.size.width)
    {
      background2.position = CGPointMake(background2.position.x + background1.size.height, background1.position.y) 
    }
like image 184
Matthew Stromberg Avatar answered Sep 28 '22 06:09

Matthew Stromberg


I've made a class for that. Currently it's written for Swift 5.0 or 4.2, and it supports top, bottom, left and right directions.

Check it out and see if it helps you, it's called InfiniteScrollingBackground: https://github.com/ThiagoAM/InfiniteScrollingBackground

like image 30
ThiagoAM Avatar answered Sep 28 '22 05:09

ThiagoAM