New To SpriteKit, Helping Tip Number #1

Are you new to SpriteKit? Is your game CPU high or glitching as you play it? There can be multiple reasons for this, but let’s look at one of the rookie or a common mistake of someone who is new to Spritekit. Overloading the animating and rendering process of the game scene with your code. What does this mean? Let’s have a look.

In the traditional iOS view, the contents of a view are rendered once and only when the model’s contents change do they render again. This model works very well because in practice most view content is static. SpriteKit, on the other hand continuously updates the scene contents and renders it to ensure that animation is smooth and accurate because it is designed explicitly for dynamic content.

The process of animating it is tied to a scene object SKScene. Here is the model below.

Basically, you have 16ms to run your code and Apple’s code before the scene is rendered. Let unroll this for a breakdown.

The red section is where Apple’s SceneKit and other frameworks run. The other parts belong to you, and you can add code to each section in you SKScene’s class. If you add to much work in any of these sections you make Spritekit’s work too hard, then the process becomes longer than 16ms increasing your framerate, CPU and possibly causing your game to glitch.

A common mistake is to have lots of code that trigger actions in your game in either the “override func update(_ currentTime: TimeInterval)” or “override func didSimulatePhysics()”. Keep in mind code run in these sections get called many times every second. Always evaluate if the code needs to be here, can it be triggered by a timer or by an action somewhere else.

There is also the opportunity for threading here as well. You can get work done in the background thread as long as SpriteKit’s handling of actions, physics, and constraints doesn’t depend on that work. Running it in parallel with the other 16ms can help reduce strain on the CPU.

If you fancy a further read on this give Apple’s documentation a try, in all honesty, their documentation has nearly everything you need to know.

https://developer.apple.com/library/content/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Introduction/Introduction.html#//apple_ref/doc/uid/TP40013043-CH1-SW1

Happy Coding!

Can’t wait to see what will happen next.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s