An Introduction to iOS 7 Sprite Kit Programming

From Techotopia
Revision as of 19:56, 27 October 2016 by Neil (Talk | contribs) (Text replacement - "<table border="0" cellspacing="0">" to "<table border="0" cellspacing="0" width="100%">")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
PreviousTable of ContentsNext
An iOS 7 UIKit Dynamics TutorialAn iOS 7 Sprite Kit Game Tutorial

Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS Edition book is now available in Print ($37.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book

If you have ever had an idea for a game, but didn’t create it because you lacked the skills or time to write complex game code and logic, then look no further than Sprite Kit. Introduced as part of the iOS 7 SDK, Sprite Kit provides a way for 2D games to be developed with relative ease.

Sprite Kit provides just about everything needed to create 2D games for iOS and Mac OS X with a minimum amount of coding. Some of the features provided by Sprite Kit include animation, physics, collision detection and special effects. Most of these features can be harnessed within a game with just a few method calls.

In this, and the next three chapters, the topic of games development with Sprite Kit will be covered with the objective of bringing the reader up to a level of competence to begin creating games whilst also providing a knowledge base on which to develop further Sprite Kit development skills.


What is Sprite Kit?

Sprite Kit is a programming framework that makes it easy for the developer to implement 2D based games that run on iOS and OS X. It provides a range of classes that support the rendering and animation of graphical objects (otherwise known as sprites) that can be configured to behave in specific programmer defined ways within a game. Through use of actions, a wide variety of activities can be run on sprites such as animating a character so that it appears to be walking, making a sprite follow a specific path within a game scene or changing the color and texture of a sprite in real-time.

Sprite Kit also includes a physics engine allowing physics related behavior to be imposed on sprites. A sprite can, amongst other things, be made to move by subjecting it to a pushing force, configured to behave as though affected by gravity, or to bounce back from another sprite as the result of a collision.

In addition, the Sprite Kit particle emitter class provides a useful mechanism for creating special effects within a game such as smoke, rain, fire and explosions. A range of templates for existing special effects is provided with Sprite Kit along with an editor built into Xcode for creating custom particle emitter based special effects.

The Key Components of a Sprite Kit Game

A Sprite Kit game will typically consist of a number of different elements.

Sprite Kit View

Every Sprite Kit game will have at least one SKView class. An SKView instance sits at the top of the component hierarchy of a game and is responsible for displaying the game content to the user. It is a subclass of the UIView class and, as such, has many of the traits of that class including an associated view controller.


A game will also contain one or more scenes. One scene might, for example, display a menu when the game first starts while additional scenes may represent multiple levels within the game. Scenes are represented in a game by the SKScene class which is a subclass of the SKNode class.


Each scene within a Sprite Kit game will have a number of Sprite Kit node children. These nodes fall into a number of different categories, each of which has associated with it a dedicated Sprite Kit node class. These node classes are all subclasses of the SKNode class and can be summarized as follows:

  • SKSpriteNode – Draws a sprite with a texture. This will typically be used for creating image based characters or objects in a game, such as a spaceship, animal or monster.
  • SKLabelNode – Used to display text within a game such as menu options, the prevailing score or a “game over” message.
  • SKShapeNode – Allows nodes to be created containing shapes defined using Core Graphics paths. If a sprite is required to display a circle, for example, the SKShapeNode class could be used to draw the circle as an alternative to texturing an SKSpriteNode with an image of a circle.
  • SKEmitterNode – The node responsible for managing and displaying particle emitter based special effects.
  • SKVideoNode – Allows video playback to be performed within a game node.
  • SKEffectNode – Allows Core Image filter effects to be applied to child nodes. A sepia filter effect, for example, could be applied to all child nodes of an SKEffectNode.
  • SKCropNode – Allows the pixels in a node to be cropped subject to a specified mask.

Physics Bodies

Each node within a scene has the option to have associated with it a physics body. Physics bodies are represented by the SKPhysicsBody class. Assignment of a physics body to a node brings a wide range of additional possibilities in terms of the behavior that can be associated with a node. When a node is assigned a physics body it will, by default, behave as though subject to the prevailing forces of gravity within the scene. In addition, the node can be configured to behave as though having a physical boundary. This boundary can be defined as a circle, a rectangle or a polygon of any shape.

Once a node has a boundary, collisions between other nodes can be detected and the physics engine used to apply real-world physics to the node such as causing it to bounce when hitting other nodes. The use of contact bit masks can be employed to specify the types of nodes for which contact notification is required.

The physics body also allows forces to be applied to nodes, such as propelling a node in a particular direction across a scene using either a constant or one time impulse force. Physical bodies can also be joined together using a variety of different join types (such as sliding, fixed, hinged and spring based attachments).

The properties of a physics body (and therefore the associated node) may also be changed. Mass, density, velocity and friction are just a few of the properties of a physics body available for modification by the game developer.

Physics World

Each scene in a game has its own physics world object in the form of an instance of the SKPhysicsWorld class. A reference to this object, which is created automatically when the scene is initialized, may be obtained by accessing the physicsWorld property of the scene. The physics world object is responsible for managing and imposing the rules of physics on any nodes in the scene with which a physics body has been associated. Properties are available on the physics world instance to change the default gravity settings for the scene and also to change the speed at which the physics simulation runs.


An action is an activity that is performed by a node in a scene. Actions are the responsibility of SKAction class instances which are created and configured with the action to be performed. That action is then run on one or more nodes. An action might, for example, be configured to perform a rotation of 90 degrees. That action would then be run on a node to make it rotate within the scene. The SKAction class includes a wide range of action types including fade in, fade out, rotation, movement and scaling. Perhaps the most interesting action involves animating a sprite node through a series of texture frames.

Actions can be categorized as sequence, group or repeating actions. An action sequence specifies a series of actions that are to be performed consecutively whilst group actions specify a set of actions to be performed in parallel. Repeating actions are configured to restart after completion. An action may be configured either to repeat a set number of times or to repeat indefinitely.


Transitions occur when a game changes from one scene to another. Whilst it is possible to immediately switch from one scene to another, a more visually pleasing result might be achieved by animating the transition in some way. This can be implemented using the SKTransition class which provides a number of different pre-defined transition animations such as sliding the new scene down over the top of the old scene, or presenting the effect of doors opening to reveal the new scene.

Texture Atlas

A large part of developing games involves handling images. Many of these images serve as textures for sprites. Whilst it is possible to add images to a project individually, Sprite Kit also allows images to be grouped together into a texture atlas. Not only does this make it easier to manage the images, but it also brings efficiencies in terms of image storage and handling. Typically the texture images for a particular sprite animation sequence would be stored in a single texture atlas whilst another atlas might store the images for the background of a particular scene.

An Example Sprite Kit Game Hierarchy

To aid in visualizing how the various Sprite Kit components fit together, Figure 56-1 outlines the hierarchy for a simple game:

An Example iOS 7 Sprite Kit game hierarchy

Figure 56-1

In this hypothetical game, a single SKView instance has two SKScene children, each of which has its own SKPhysicsWorld object. Each scene, in turn, has two node children. In the case of both scenes, the SKSpriteNode instances have been assigned SKPhysicsBody instances.

The Sprite Kit Game Rendering Loop

When working with Sprite Kit, it helps to have a basic understanding of the way in which the animation and physics simulation process works. This can best be described by looking at the Sprite Kit frame rendering loop.

Sprite Kit performs the work of rendering a game using a game rendering loop. Within this loop, Sprite Kit performs a variety of tasks to render the visual and behavioral elements of the currently active scene, with an iteration of the loop being performed for each successive frame displayed to the user.

Figure 56-2 provides a visual representation of the frame rendering sequence performed in the loop:

The iOS 7 Sprite Kit Game Rendering Loop

Figure 56-2

When a scene is displayed within a game, Sprite Kit enters the rendering loop and repeatedly performs the same sequence of steps as shown above. At a number of points in this sequence, the loop will make calls to your game providing the opportunity for the game logic to respond when necessary.

Before performing any other tasks, the loop begins by calling the update method of the corresponding SKScene instance. It is within this method that the game should perform any tasks prior to the frame being updated, such as adding additional sprites or updating the current score.

The loop then evaluates and implements any actions that are pending on the scene, after which the game is given the opportunity to perform more tasks via a call to the didEvaluateActions method.

Next, physics simulations are performed on the scene followed by a call to the scene’s didSimulatePhysics method where the game logic may react where necessary to any changes as a result of the physics simulation.

Finally, the SKView instance renders the new scene frame before the loop sequence repeats once again.


Sprite Kit provides a platform for the creation of 2D games on iOS and Mac OS X. Games are comprised of an SKView instance with an SKScene object for each scene of the game. Scenes contain nodes that represent the characters, objects and items in the game. A variety of node types are available, all of which are subclassed from the SKNode class. Each node can have associated with it a physics body in the form of an SKPhysicsBody instance. A node with a physics body will be subject to physical forces such as gravity and, when given a physical boundary, collisions with other nodes may also be detected. Actions are configured using the SKAction class, instances of which are then run by the nodes on which the action is to be performed.

The rendering of a Sprite Kit game takes place within the game loop with one loop being performed for each frame of the game. At a variety of points in this loop, the application will be given the opportunity to perform tasks as needed to implement and manage the underlying game logic.

Having provided a high level overview in this chapter, the next three chapters will take a more practical approach to exploring the capabilities of Sprite Kit through the creation of a simple game.

Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS Edition book is now available in Print ($37.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book

PreviousTable of ContentsNext
An iOS 7 UIKit Dynamics TutorialAn iOS 7 Sprite Kit Game Tutorial