Geoff H
Geoff H

Reputation: 3247

How to scroll tiled sprites without gaps or glitches appearing inbetween in SpriteKit

I have a sideways scrolling tiled background of SkSpriteNodes in SpriteKit and occasionally thin gaps keep appearing between the tiles as they are not butting-up to eachother exactly. The code I am using is this;

func updateBackground() {

    worldNode.enumerateChildNodesWithName("Background", usingBlock: { node, stop in

        if let background = node as? SKSpriteNode {

            let scrollAmount = CGPoint(x: -self.kBackgroundSpeed * CGFloat(self.deltaTime), y: 0)
            background.position += scrollAmount

            if background.position.x < -background.size.width {

                background.position += CGPoint(x:background.size.width * CGFloat(self.kNumBackgroundSprites), y: 0)

            }

        }

    })

}

What do I need to do to this code to stop the gaps from appearing?

Upvotes: 0

Views: 337

Answers (2)

Alain T.
Alain T.

Reputation: 42133

If you're moving a bunch of nodes at the same time and by the same displacement, you should consider creating a "container" SKNode in which you add all these nodes as children and moving the container instead of each node individually.

Upvotes: 2

TwoStraws
TwoStraws

Reputation: 13127

To avoid minor errors like this one, you should consider having SpriteKit move the background for you using an SKAction. Something like this ought to do the trick:

let moveLeft = SKAction.moveByX(-backgroundTexture.size().width, y: 0, duration: 20)
let moveReset = SKAction.moveByX(backgroundTexture.size().width, y: 0, duration: 0)
let moveLoop = SKAction.sequence([moveLeft, moveReset])
let moveForever = SKAction.repeatActionForever(moveLoop)

background.runAction(moveForever)

If you have two backgrounds moving like this, you should be able to get a seamless effect fairly easily. This approach is also less CPU intensive than updating everything by hand, as you might imagine.

I wrote a Flappy Bird SpriteKit tutorial that solves just this problem; you might find it interesting reading.

Upvotes: 1

Related Questions