In this tutorial I'll show you some of the best practices that can help you to tackle the most annoying issues in SpriteKit.

Update: check out my latest article about building SpriteKit games

Scene size

First of all, the size of a scene is always relative. It's pretty easy to fix this issue, you just have to set the scene size after the view did layout the subviews. With this trick the size of the scene will always match the size of your device screen.

NOTE: do NOT use the frame of the scene, use the size for coordinate geometry!

You can watch for changes inside your scene, there is a method for this purpose.

Scene rotation

If you want to have rotation support in your game, that's pretty easy too. You just have to implement one method inside your view controller, and delegate the size changes forward to your scene.

Pause, resume scene

In the past, this was a big issue in SpriteKit, because the scene always resumed itself after coming back from the background mode. Other issues happend as well, if you tried to pause the SKView. Fortunately nowadays these properties are working as it is expected, so no extra hacks like this one are needed. So remember, you can just set the isPaused property on the SKView and you are ready to go. Nice job Apple! ;)

Gradient SKTexture

Creating a gradient texture was also really painful, but now it's just one simple extension around the SKTexture class. You have to use a CILinearGradient filter, but be careful: you can NOT use this filter on a SKEffectNode, that will raise an exception and your app will crash. Anyway, here is the code:

Now you can use your linear gradient texture as usual, with any node objects.

SKNode zPosition

ALWAYS specify zPosition for every element in your scene.

Lesson learned, in the past I thought the z index is going to be calculated dynamically based on some kind of layers, or by the order of the addition of the node, but hell no. You should always set an explicit zPosition value (including SKShapeNodes) if you want to avoid some serious bug hunting in the future.

NOTE: You can find an example source code for this article on gitlab.