SpriteKit Tutorial for Beginners

In this SpriteKit tutorial, you will learn how to create a simple 2D game using SpriteKit, Apple’s 2D game framework, while writing in Swift 4! By Brody Eller.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Game Over, Man!

Now, create a new scene that will serve as your “You Win” or “You Lose” indicator. Create a new file with the iOS\Source\Swift File template, name the file GameOverScene and click Create.

Add the following to GameOverScene.swift:

import SpriteKit

class GameOverScene: SKScene {
  init(size: CGSize, won:Bool) {
    super.init(size: size)
    
    // 1
    backgroundColor = SKColor.white
    
    // 2
    let message = won ? "You Won!" : "You Lose :["
    
    // 3
    let label = SKLabelNode(fontNamed: "Chalkduster")
    label.text = message
    label.fontSize = 40
    label.fontColor = SKColor.black
    label.position = CGPoint(x: size.width/2, y: size.height/2)
    addChild(label)
    
    // 4
    run(SKAction.sequence([
      SKAction.wait(forDuration: 3.0),
      SKAction.run() { [weak self] in
        // 5
        guard let `self` = self else { return }
        let reveal = SKTransition.flipHorizontal(withDuration: 0.5)
        let scene = GameScene(size: size)
        self.view?.presentScene(scene, transition:reveal)
      }
      ]))
   }
  
  // 6
  required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

There are six parts to point out here:

  1. Set the background color to white, same as you did for the main scene.
  2. Based on the won parameter, the message is set to either "You Won" or "You Lose".
  3. This is how you display a label of text on the screen with SpriteKit. As you can see, it's pretty easy. You just choose your font and set a few parameters.
  4. Finally, this sets up and runs a sequence of two actions. First it waits for 3 seconds, then it uses the run() action to run some arbitrary code.
  5. This is how you transition to a new scene in SpriteKit. You can pick from a variety of different animated transitions for how you want the scenes to display. Here you've chosen a flip transition that takes 0.5 seconds. Then you create the scene you want to display, and use presentScene(_:transition:) on self.view.
  6. If you override an initializer on a scene, you must implement the required init(coder:) initializer as well. However this initializer will never be called, so you just add a dummy implementation with a fatalError(_:) for now.

So far so good! Now you just need to set up your main scene to load the game over scene when appropriate.

Switch back to GameScene.swift, and inside addMonster(), replace monster.run(SKAction.sequence([actionMove, actionMoveDone])) with the following:

let loseAction = SKAction.run() { [weak self] in
  guard let `self` = self else { return }
  let reveal = SKTransition.flipHorizontal(withDuration: 0.5)
  let gameOverScene = GameOverScene(size: self.size, won: false)
  self.view?.presentScene(gameOverScene, transition: reveal)
}
monster.run(SKAction.sequence([actionMove, loseAction, actionMoveDone]))

This creates a new "lose action" that displays the game over scene when a monster goes off-screen. See if you understand each line here, if not refer to the explanation for the previous code block.

Now you should handle the win case too; don't be cruel to your players! :] Add a new property to the top of GameScene, right after the declaration of player:

var monstersDestroyed = 0

And add this to the bottom of projectileDidCollideWithMonster(projectile:monster:):

monstersDestroyed += 1
if monstersDestroyed > 30 {
  let reveal = SKTransition.flipHorizontal(withDuration: 0.5)
  let gameOverScene = GameOverScene(size: self.size, won: true)
  view?.presentScene(gameOverScene, transition: reveal)
}

Here you keep track of how many monsters the player destroys. If the player successfully destroys more than 30 monsters, the game ends and the player wins the game!

Build and run. You should now have win and lose conditions and see a game over scene when appropriate!

SpriteKit Tutorial

Where to Go From Here?

And that's a wrap! You can download the project files at the top or bottom of this page.

I hope you enjoyed learning about SpriteKit and are inspired to make your own game. If you have any questions or comments about this SpriteKit tutorial, please join the discussion below!

If you want to learn more about SpriteKit, you should check out our book: 2D Apple Games by Tutorials:

In this book we teach you everything you need to know to make great games for iOS, tvOS, watchOS and macOS: from physics, to tile maps, to particle systems, and even how to make your games "juicy" with polish and special effects!

Brody Eller

Contributors

Brody Eller

Author

Felicity Johnson

Tech Editor

Essan Parto

Final Pass Editor

Richard Critz

Team Lead

Over 300 content creators. Join our team.