A first step in starting game development in SpriteKit with Swift language
SpriteKit is Apple’s official framework for building 2D games. Before the launch of SpriteKit and SceneKit (Apple’s 3D framework for games) there were 3 rd party solutions you could use to develop games for iOS, including Cocos2d, Cocos2d-x, Marmalade and Sparrow etc. While the other frameworks are also quite powerful and have lots of community support, SpriteKit and SceneKit enjoy the benefit of official Apple support and optimization to run on the platform natively.
This tutorial is a first step in starting game development in SpriteKit with Swift language (a new language for OS X and iOS app development). It is assumed that the reader is familiar with Swift and UIKit so details about the language itself will not be provided. If you are not yet proficient in Swift it is recommended you read up and follow some tutorials on the language before you continue on this tutorial.
This tutorial was created by Ahmed Belal at ZENVA. We create and resell online courses on game, app and web development. Feel free to check any of our iOS courses:
You may have heard the word “sprite” before or it may be quite new to you. In simple words a sprite is, in game development world, a single graphic that may be moved or otherwise manipulated on screen individually. For example a player character could be one sprite and every enemy character could be a separate sprite. Traditionally sprites are animated using different images with slight variations between each frame. When these images are swapped in and out in a sequence quickly it gives the illusion of a fluid animation. This is the same technique as is used in movies where the movie is actually still images being shown for a short time before being replaced by the next image or “frame”.
Sprite images are stored in a compound image called a “spritesheet” which packs in all the images close into a single file. Every individual image is called a “sprite frame.” As to why spritesheets are used instead of separate images you will have to look it up yourself but a very short explanation is that it provides great loading, storage and drawing advantages.
A sample spritesheet for a swimming fish with 13 frames
This is just a basic description of some of the SpriteKit processes and structures. You can skip ahead if you want to get straight to the code part.
Objects that are drawn on screen inherit from the SKNode class much like UIButton, UITextField and UIImageView etc inherit from a UIView class in a UIKit application.
SpriteKit draws its nodes (“Scenes”) in what is called a “node tree hierarchy”, not very different from an HTML DOM tree. If you are coming from frameworks like Cocos2d will already be familiar with the node tree hierarchy. For newcomers: a node tree is like an actual tree structure. Each node has a position relative to its parent not unlike the frame of a view object that defines position of the view relative to its superview in any iOS application.
Different screens are implemented as SKScene objects or subclasses of SKScene class. Different “nodes” or objects are added to the current scene object for them to appear on screen. So in the SpriteKit world, SKScene objects work similar to UIViewController objects. You add sprites and buttons and other controls to the scene and they appear on the screen if the scene in question is currently loaded in view.
A hypothetical Main Menu scene hierarchy
The same holds for all other node objects. For example, an SKSpriteNode object (AKA sprite object) can have multiple sprites added as children nodes. If you were to move, rotate or scale etc. the parent sprite the children will be moved, scaled and rotated with the parent. All child nodes are affected by changes on the parent.
Right, let’s start off with the actual development and I’ll explain things as we do them.
First off, you want to create a new project. Select “Game” template from the New Project window under the Application family in the iOS category.
Create a new “Game” Project
Now select Swift as the language, SpriteKit as the technology and Universal for the devices option. Fill in product name and bundle identifier, select a location and Xcode will create a project for you.
Once the project has been created you should have a similar Project Navigator tree in your left pane:
You should have an image with the name of “Spaceship” in your Images.xcassets catalog. We will be using this image for our sprite in this tutorial.
Your storyboard file will have a single view controller of the class GameViewController. This class has already been set up by Xcode to load your GameScene scene object as soon as the application starts. For the scope of this tutorial we won’t bother with the code of GameViewController and go straight to GameScene.swift file.
When you open the scene file you will see that good guy Xcode has already created some boilerplate code for you. Go ahead and run the project. At this stage you should be able to see a “Hello World” label smack dab in the center of your device or simulator. Rotate the device and the whole scene rotates to fill the screen. You can disable screen rotation in GameViewController but we won’t be touching that subject in this tutorial.
Now tap anywhere on the screen and you will see a spaceship spawn on that point, cursed to rotate right there till the end of time. Multiple taps will continue spawning rotating spaceships.
Right, now we need to delete everything from the GameScene didMoveToView and touchesBegan functions. Add the following code to the didMoveToView function:
1. var sprite = SKSpriteNode(imageNamed:"Spaceship") 2. sprite.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame)) 3. self.addChild(sprite)
Now run the application and you should see a lonely spaceship appear in the center of the screen. Tapping anywhere won’t do anything as we deleted everything from the touchesBegan function. Pat yourself on the back; you’ve just added a new sprite to a game. You, my dear friend, are officially a game developer now!
I’ll explain each line now:
The first line creates a “sprite” variable and initializes it with the image “Spaceship” from the image catalog. This is the same image that was added by Xcode to our project on creation. The second line positions the sprite in the center of the screen. The third line actually adds the sprite to the scene node tree so it shows on the screen.
I have to admit, a lonely, stationary spaceship is no fun. So let’s go ahead and make our spaceship move. Let’s move that spaceship, though we won’t be achieving hyperdrive speeds just yet. Add the following lines before the self.addChild(sprite) part:
1. let moveAction = SKAction.moveTo(CGPoint(x: 0.0, y:0.0), duration: 5.0) 2. sprite.runAction(moveAction)
Run the application now and you should see the spaceship slink towards the bottom left out of sight.
The first line in this snippet creates a “moveTo” action with a 5 second duration. The second line tells the sprite variable to run that action.
In SpriteKit if you wish to do animations you run an “action” on a sprite. Be it move, rotate, scale or something else you create an action for it and then tell your required sprite to run that action. You can also associate a “key” to each action so you could reference it later in case you want to stop an action midway or something else. There are actions available like moveTo, moveBy, scaleTo, scaleBy, rotateTo and rotateBy etc. You can also create your own custom actions following the SKAction guidelines.
Complex actions usually require running a couple of actions in a sequence. You can create a sequence action like SKAction.sequence(…) passing in a list of actions. When you run the sequence action the sprite will follow all the actions in the sequence as they were supplied.
Play around with new sprites and actions. Try out the SKAction.moveBy, SKAction.rotateTo and other actions. Add new images to the project and explore all the actions you can do by manipulating node properties.
Download the source code of the tutorial here.