UI Hosted SpriteKit View Tutorial – Part 2

In the second and final part of our tutorial we are going to add some content to our game. Again our goal is to be able to use Xcode’s level editor so that the game can be extended easily. We also want to add some SpriteKit specific characteristics like gravity.

So let’s add a SpriteKit Scene file. We are going to call it “GameScene”. Since we have referenced this title in code already, make sure to spell it out exactly. Here is a look at what I ended up with after some editing:

There are a couple of things to note. The is sized to 300 x 300 pixels – exactly the same size as our SKView in the storyboard editor. It has a gravity of x: 0, y: -9.8. We also have four elements of type ColorSprite. A board element also sized to 300 x 300 pixels with a custom color of orange, two obstacles that are each 32 x 8 pixels and finally one ball element with a size of 32 x 32 pixels.

In order to have objects collide we need to set up their body type. So set the 2 obstacles to ‘bounding rectangle’ and the ball to ‘bounding circle’ in the Physics Definition menu. When setting the body type a bunch of new value settings will be revealed. We want to make sure to uncheck the “Affected by Gravity” for our 2 obstacles. Finally open the Custom Class Inspector for the scene and set the Custom Class for our first scene to GameScene. We don’t have that class yet but will add it right now.

Add a new file of type “Swift File” and name it GameScene. Then replace the code in it with the following:

This is just a bare bones implementation of a scene. We only do one thing here. In our didMove(to:) function we create an SKPhysicsBody from a frame of our entire scene. That will give our balls and other objects something to collide with and we end up with a box of sorts. To see that behavior in action go to the ViewController class and implement the loadLevel function like so:

Now when we run the app in the simulator we should see some action. We have to tap the Level 1 button of course, so let’s go ahead and have the app load the first level on start-up. In the ViewController’s viewDidLoad function add this line right at the end:

Now the game loads the first level when the application is launched.

It is time to add the second level. An easy way to accomplish this would be to duplicate it in Xcode’s project tree like we can do with other files. Unfortunately this doesn’t work as of Xcode 8.3, so we’ll have to do it in the Finder and then drag the copy into the source tree. We have referenced the second level as “GameScene2” in our ViewController, so we need to stick with that label. Here is what I came up with for the second level’s layout:

So there you have it. We have a view-based iOS app with an embedded SpriteKit view. The completed project is available for download here.