How to Make a Game Like Mega Jump With Sprite Kit and Swift: Part 1/2

In part one of this two-part tutorial series, you’ll start creating a game like Mega Jump, and implement the overall scene, physics, and sound effects using Swift and Sprite Kit! By Michael Briscoe.

Leave a rating/review
Save for later
Share

Update April 17, 2015: This tutorial was updated for Xcode 6.3 / Swift 1.2 by Michael Briscoe.

Original post by tutorial team member Toby Stephens.

In this two-part tutorial series, you will use Sprite Kit and Swift to create a game in the style of Mega Jump. If you’ve somehow missed trying Mega Jump from the App Store, it’s quite a popular vertical jumping game with really nice graphics and addictive gameplay. As you build your game, you’ll learn how to use a number of Sprite Kit’s capabilities, including the physics engine, collision detection, accelerometer control and scene transitions.

If you are new to Sprite Kit, it would be best to work your way through Ray’s Sprite Kit Tutorial for Beginners before starting this tutorial series.

But if you’re comfortable with the basics of Sprite Kit, then jump right in!

Note: The game you’ll build will eventually use the accelerometer to control horizontal movement. That means you’ll need a paid developer account and a device to test on to get the most out of this tutorial.

Getting Started

You are going to create a game similar to Mega Jump. Yours will obviously be a truly amazing game and so it needs a truly amazing title. As everyone knows, “uber” is better than “mega,” so let’s call your game “Uber Jump.” ;]

At its heart, a game like Mega Jump is a physics game. The game hurls the player character up the screen and from that point the player must fight against gravity to get as high as they can. Collecting coins boosts the player upward while platforms provide temporary respite along the way.

Uber Jump will take the same model, initially thrusting your player character upward and continuously applying gravity to pull them down. Collecting stars along the way will propel the player further on their journey upward, taking care of the up and down (y-axis) portion of the player’s movement (miss too many stars and you fall down though!). The accelerometer will handle the player’s left and right movement (x-axis).

The result will be a complex, hybrid physics manipulation, as you both apply forces to the player node and also directly change its velocity. It’ll also be lots of fun!

To begin, you need a brand new Sprite Kit Xcode project. Fire up Xcode, select File\New\Project, choose the iOS\Application\SpriteKit Game template and click Next.

NewProject

Enter UberJump for the Product Name, set the Language to Swift, and iPhone for Devices and then click Next.

NewProjectName

Choose somewhere to save the project and click Create.

Before getting down to business, you’ll do some preliminary setup. Locate the GameScene.sks file in the Project Navigator. You won’t be using this, so select it and press the delete key. When the warning alert shows, choose Move to Trash.

DeleteGameScene

Now open GameViewController.swift and delete the unarchiveFromFile SKNode extension at the top of the file, as you won’t be needing this extraneous code. Then replace viewDidLoad with the following:

override func viewDidLoad() {
  super.viewDidLoad()
        
  let skView = self.view as! SKView
        
  skView.showsFPS = true
  skView.showsNodeCount = true
                
  let scene = GameScene(size: skView.bounds.size)
  scene.scaleMode = .AspectFit
        
  skView.presentScene(scene)
}

Build and run to make sure everything is working so far.

FirstRun

Don’t worry about the “Hello, World” text label clipping. You’ll be replacing what’s in the GameScene.swift file in just a moment, but first you have one last thing to setup. Since your game is going to use the accelerometer, you need to make sure that tilting the device doesn’t flip the game into landscape mode.

With your project selected in the Project Navigator in Xcode, select the UberJump target, go to the General settings tab and look in the Deployment Info section. Ensure that the only available device orientation is Portrait.

NewProjectPortrait

Now you are ready to start adding your game’s components. First up: the pretty pictures.

Importing the Art

Before you get down to adding Sprite Kit nodes to your game, you need some art.

Download the graphics resources for this project, drag the contents into your Xcode project. Make sure that “Destination: Copy items if needed” is checked and that your UberJump target is selected.

uj_asset_files

I’ve split the artwork into background tiles and game assets.

Background tiles are large tiles that scroll up and down the screen as the player moves:

uj_bg_thumb

The game assets are all of the sprites, such as the player character, platforms and stars:

Player@2x

The game assets are stored in a texture atlas for efficiency. You can learn more about texture atlases in Sprite Kit in this tutorial.

Note: I pieced together the graphics for Uber Jump using the amazing artwork provided by lostgarden.com. This website provides high-quality graphics for devs to use in prototyping their games and is well worth a visit. You can check their exact licensing policy.

Note: I pieced together the graphics for Uber Jump using the amazing artwork provided by lostgarden.com. This website provides high-quality graphics for devs to use in prototyping their games and is well worth a visit. You can check their exact licensing policy.

Building the Scene

In your project, you can see that the Sprite Kit template has already created the GameScene class for you. This is the Sprite Kit scene that is currently showing the “Hello, World!” message when you run the game. Most of Uber Jump’s action will take place here, so open GameScene.swift and replace the contents with the following:

import SpriteKit

class GameScene: SKScene {
   
  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
  }
    
  override init(size: CGSize) {
    super.init(size: size)     
    backgroundColor = SKColor.whiteColor()
  }
}

Build and run. GameScene now displays a simple white screen. This is the blank canvas onto which you’ll add your game nodes.

Mega Jump uses parallaxed layers to produce a neat visual representation of speed. (Eg. things in front move faster than things in the background.) In Uber Jump, you’re going to produce the same effect by creating the following layers in your scene:

  • Background: a slow-moving layer that shows the distant landscape.
  • Midground: faster-moving scenery made up of tree branches.
  • Foreground: the fastest layer, containing the player character, stars and platforms that make up the core of the gameplay.
  • HUD: the top layer that does not move and displays the score labels.

First, add the background node. Open GameScene.swift and add the following method:

func createBackgroundNode() -> SKNode {
  // 1
  // Create the node
  let backgroundNode = SKNode()
  let ySpacing = 64.0 * scaleFactor
        
  // 2
  // Go through images until the entire background is built
  for index in 0...19 {
    // 3
    let node = SKSpriteNode(imageNamed:String(format: "Background%02d", index + 1))
    // 4
    node.setScale(scaleFactor)
    node.anchorPoint = CGPoint(x: 0.5, y: 0.0)
    node.position = CGPoint(x: self.size.width / 2, y: ySpacing * CGFloat(index))
    //5
    backgroundNode.addChild(node)
  }
        
  // 6
  // Return the completed background node
  return backgroundNode
}

Let’s take a closer look at what you’re doing here:

  1. First, you create a new SKNode. SKNode’s have no visual content, but do have a position in the scene. This means you can move the node around and its child nodes will move with it.
  2. You have 20 background images to stack to complete the background.
  3. Each child node is made up of an SKSpriteNode with the sequential background image loaded from your resources.
  4. Changing each node’s anchor point to its bottom center makes it easy to stack in sections.
  5. You add each child node to the background node.
  6. Finally, you return the background node.

Now you can add the background node to your scene. Still in GameScene.swift, add the following class properties:

// Layered Nodes
var backgroundNode: SKNode!
var midgroundNode: SKNode!
var foregroundNode: SKNode!
var hudNode: SKNode!
    
// To Accommodate iPhone 6
var scaleFactor: CGFloat!

You are adding properties for each of the nodes you need for the game. You only need the background node for the moment, but it doesn’t hurt to add the other node declarations now. You are also adding the scaleFactor property. This ensures that your graphics are scaled and positioned properly across all iPhone models.

To add the background to the scene, insert the following into init(size:) in GameScene.swift, just after the line that sets the background color:

scaleFactor = self.size.width / 320.0
        
// Create the game nodes
// Background
backgroundNode = createBackgroundNode()
addChild(backgroundNode)

The graphics are sized for the standard 320-point width of most iPhone models, so the scale factor here will help with the conversion on other screen sizes.

All you need to do after initializing the background node is to add it as a child to the current scene.

Build and run to see your background node displayed in the scene, as shown below:

05-BackgroundNode

Note: Although you added 20 nodes to the background node, you’ll see that the node count in the scene is only nine nodes if you’re running on a 4″ display or eight nodes if you’re running on a 3.5″ display. Sprite Kit is clever enough to include only the nodes that are actually visible at any given moment in the game.

Note: Although you added 20 nodes to the background node, you’ll see that the node count in the scene is only nine nodes if you’re running on a 4″ display or eight nodes if you’re running on a 3.5″ display. Sprite Kit is clever enough to include only the nodes that are actually visible at any given moment in the game.

Michael Briscoe

Contributors

Michael Briscoe

Author

Over 300 content creators. Join our team.