-
We are going to make an app that animates bubbles in the background that float from the bottom of the screen up towards the top.
Create a New Project
We want to use some of xCode’s SpriteKit tools, but in order to do so we need to have an SKView in our ViewController rather than a UIView.To accomplish this we will open up Xcode and create a new project, choose “Game” and press next, where we can select Swift and SpriteKit. Click Next and title the project “Animation.”
We will need to add a new CocoaTouch Class file with class titled “ViewController” and a subclass of UIViewController and then use the storyboard to click on the view (as seen below) and change the class of our view to an SKView in the “Identity Inspector” tab.Setting the Scene
Now create a new “Swift file” named “AnimationScene”
In that file, replace the bit of code they give you with this:Our class is of type “SKScene”. Think of an SKScene as a movie scene. A TV has a screen that displays scenes from a movie, and these scenes have actors and scenery and such.
• Our ViewController is like the TV
• The SKView is like the TV screen
• The SKScene is like a movie scene
• SKNodes are like actors and scenery
•
So if we follow this analogy: A ViewController has an SKView that displays SKScenes, and these SKScenes have SKNodes.
Let’s talk about the code. The “required init” is a requirement of inheriting from SKScene. Xcode will add that for you if you don’t manually type it. The second initializer takes a size and uses that as the size for our scene and sets the anchor point to be the top left of the scene. (0,0) means bottom left for the anchor point, (1,1) means top right, so (0,1) is the top left. Update is a function from SKScene that is called before each frame. We will make good use of that later.
ViewController.swift
First, let’s get our ViewController to show this empty scene. Open up our ViewController.swift file and make the following changes.The variable “scene” holds an instance of the “AnimationScene” class we just created and sets it’s size to be the size of the screen. Because we set the class of our ViewController’s View to SKView earlier, we can now downcast it as an SKView and use it to present our empty scene.
If you run the application at this point, the screen should turn to a dark gray like the screen shown on the left. That means we are displaying the scene. (note: the check mark should not appear)Then change the AnimationScene.swift file to: