After being developing for some time with the new 2D game engine SpriteKit, I have to admit that I’m in love with it. I find it really simple to use, easy to learn and very powerful. While developing my new game, I was faced with the need to introduce parallax scrolling to give a sense of depth to the game. I have published a class on Github to easily add Parallax Backgrounds in any SpriteKit game, so if you are, like me, an iOS developer interested in SpriteKit games, here is how you can implement your own parallax effect for your SpriteKit games.
Parallax Scrolling is a 2D effect used to create a fake sense of 3D depth in a 2D game. It is based on a trick of the eye that happens when you are traveling, i.e: in a car. As you move forwards, the closest items seem to move faster than the distant ones, as if there were several layers moving at different speeds, the closer the faster. etting several images acting as background layers, and animating all of them in the same direction, but at different speeds.
Now let’s create our own Parallax Scrolling effect for our SpriteKit App. First we will create a new project in Xcode. Choose iOS -> Application -> SpriteKit Game.
Pick a name for the project, like “ParallaxBackground” and a prefix for your classes, like “PB”, and Xcode will set the initial environment and needed classes for the development of a SpriteKit app, as show here:
First, we need to do some changes to clean and set everything. We need to edit PBViewController and move the code that initializes the SKScene from viewDidLoad (where Xcode originally puts it) to viewWillLayoutSubviews. Why? because in viewDidLoad, our view still has not been presented to screen, so a lot of properties have not been set, like size, for example. It is way better to initialize the scene when our view is ready to be shown and everything has been set. To avoid the view appearing on the screen and then initializing the SKScene with a noticeable flash, we will use viewWillLayoutSubviews (called prior to viewDidAppear) instead of viewDidAppear. So our PBViewController will be like this:
- (void)viewDidLoad { [super viewDidLoad]; } - (void) viewWillLayoutSubviews { [super viewWillLayoutSubviews]; // Configure the view. SKView * skView = (SKView *)self.view; if (!skView.scene) { // because viewWillLayoutSubviews is called twice! skView.showsFPS = YES; skView.showsNodeCount = YES; // Create and configure the scene. SKScene * scene = [[PBMyScene alloc] initWithSize:skView.bounds.size]; scene.scaleMode = SKSceneScaleModeAspectFill; // Present the scene. [skView presentScene:scene]; } }
Now we should delete the Spaceship.png and edit the touchesBegan:withEvent: method, so no spaceship is shown if we touch the screen. Then, we can start writing our parallax scrolling code.