Search code examples
swiftmultithreadingsprite-kitbackground-process

Runnning SpriteKit processes in background threads to improve CPU usage


I'm building my first game with Swift and SpriteKit and I've been having many problems with CPU use and consequently battery life. I wanted to know if it was common practice to run certain tasks, like instantiating bad guys, in background threads; and if so how I would go about implementing that?


Solution

  • If this is your first game, you may not want to go crazy with multiple threads unless you really know what you are doing. Be aware that manipulating SKNodes must be done on the same thread that SKView(Private) _update: is run on. This is the same thread that runAction blocks are run on. If you don't you'll crash. In a SpriteKit game I was working on, I was multi-threaded and was not using SKAction or runAction for any updating. I had to eventually add runAction for tree management. I'm currently in the process of re-writing this in OpenGL because of this.

    There are certain tasks which make sense to offload, like loading files or even network calls. You should be using GCD for those types of things. Keep in mind that multi-threading does not reduce CPU time as you are imagining.

    Odds are your code is doing something bad which is causing you to eat CPU time. Even if you multi-thread, you will end up with the same high CPU but with the problem of a more difficult time debugging. Note I'm not saying its impossible.

    Spend the time and figure out really why your CPU usage is high. Based on your other threads, you are not doing a lot.

    As an experiment take that spaceship example and run it on your device. Keep adding ships and see what it does to the CPU. Find out how many you have to add before CPU and FPS degrade. Compare that to your game, keeping in mind that the spaceship example is just a simple demo.