In this game, we will take control of a little rabbit that is trying to escape from the top hat of a magician, where it is trapped. To achieve its objective, our main character will need to run through magic doors until it gets the ace of diamonds that will let the rabbit escape.
In this chapter, we are going to see how to create the main character's sprite and add it to the scene. On the other hand, we will learn how to set a background for the game. In the preceding pages, we have seen a lot of properties and methods that will help us reach our current goal.
Let's start by cleaning off the unnecessary files and content in the project. We are going to generate the screens programmatically so that you can delete the sks
file:
Right-click on the
GameScene.sks
file.Choose Delete.
Ensure that you click on the Move to Trash button.
Next, adapt the GameViewController
class in order to avoid initializing the scene from the file that we have just removed. Replace the viewDidLoad
method from this class with the following block of code:
override func viewDidLoad() { super.viewDidLoad() let scene = GameScene(size: view.bounds.size) // Configure the view. let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) }
We have just modified the old line, which looks like this:
if let scene = GameScene(fileNamed:"GameScene") {
We replaced the preceding line of code with the following code:
let scene = GameScene(size: view.bounds.size)
This way, we initialized the scene using the init(size:)
method of the SKScene
class, to which we pass a size
value as an input parameter in the form of view.bounds.size
. We are using the bounds property of the SKView
class, which corresponds to a rectangle that occupies the whole size of the screen.
Now, it's time to clean the GameScene
class. Therefore, open it and replace the didMoveToView
method with the following piece of code:
override func didMoveToView(view: SKView) { }
Replace the touchesBegan
method with the following code:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { }
The project is now ready to be updated with our brand-new code, but you can run it just to ensure that we haven't broken anything.