Johno2110
Johno2110

Reputation: 1131

Parallax Scrolling SpriteKit

I have found a tutorial on parallax scrolling in spritekit using objective-C though I have been trying to port it to swift without much success, very little in fact.

Parallax Scrolling

Does anyone have any other tutorials or methods of doing parallax scrolling in swift.

Upvotes: 4

Views: 3105

Answers (1)

Bill peek
Bill peek

Reputation: 120

This is a SUPER simple way of starting a parallax background. WITH SKACTIONS! I am hoping it helps you understand the basics before moving to a harder but more effective way of coding this. So I'll start with the code that get a background moving and then you try duplicating the code for the foreground or objects you want to put in your scene.

//declare ground picture. If Your putting this image over the top of another image (use a png file).
    var groundImage = SKTexture(imageNamed: "background.jpg")

    //make your SKActions that will move the image across the screen. this one goes from right to left.
    var moveBackground = SKAction.moveByX(-groundImage.size().width, y: 0, duration: NSTimeInterval(0.01 * groundImage.size().width))

    //This resets the image to begin again on the right side.
    var resetBackGround = SKAction.moveByX(groundImage.size().width, y: 0, duration: 0.0)

    //this moves the image run forever and put the action in the correct sequence.
    var moveBackgoundForever = SKAction.repeatActionForever(SKAction.sequence([moveBackground, resetBackGround]))

    //then run a for loop to make the images line up end to end.
    for var i:CGFloat = 0; i<2 + self.frame.size.width / (groundImage.size().width); ++i {
        var sprite = SKSpriteNode(texture: groundImage)
        sprite.position = CGPointMake(i * sprite.size.width, sprite.size.height / 2)
        sprite.runAction(moveBackgoundForever)
        self.addChild(sprite)
    }
}
//once this is done repeat for a forground or other items but them run at a different speed.

/*make sure your pictures line up visually end to end. Just duplicating this code will NOT work as you will see but it is a starting point. hint. if your using items like simple obstructions then using actions to spawns a function that creates that obstruction maybe a good way to go too. If there are more then two separate parallax objects then using an array for those objects would help performance. There are many ways to handle this so my point is simple: If you can't port it from ObjectiveC then rethink it in Swift. Good luck!

Upvotes: 4

Related Questions