Quantcast
Channel: Kodeco | High quality programming tutorials: iOS, Android, Swift, Kotlin, Unity, and more
Viewing all articles
Browse latest Browse all 4387

How To Make a Game Like Space Invaders with Sprite Kit and Swift Tutorial: Part 1

$
0
0

SpaceInvaders-feature

Update 05/10/2016: Updated for Xcode 7.3 by Ryan Ackermann. Original tutorial by Joel Shapiro and previously updated by Riccardo d’Antoni.

Space Invaders is one of the most important video games ever developed. Created by Tomohiro Nishikado and released in 1978 by Taito Corporation, it earned billions of dollars in revenue. It became a cultural icon, inspiring legions of non-geeks to take up video games as a hobby.

In this tutorial, you’ll build an iOS version of Space Invaders, using Swift and Sprite Kit, Apple’s 2D game framework.

This tutorial assumes you are familiar with the basics of Swift and Sprite Kit. If you are completely new to Sprite Kit, you should go through our Sprite Kit tutorial for beginners first.

Also, you will need Xcode 7.3 or later, an iPhone or iPod Touch running iOS 9 and an Apple developer account in order to get the most out of this tutorial. That is because you will be moving the ship in this game using the accelerometer, which is not present on the iOS simulator. If you don’t have an iOS 9 device or developer account, you can still complete the tutorial — you just won’t be able to move your ship.

Without further ado, let’s get ready to blast some aliens!

An original Space Invaders arcade cabinet

An original Space Invaders arcade cabinet

Getting Started

Apple provides an template named Game which is pretty useful if you want to create your next smash hit from scratch. However, in order to get you started quickly, download the starter project for this tutorial. It’s based on the Sprite Kit Game template and already has some of the more tedious work done for you.

Once you’ve downloaded and unzipped the project, open the project in Xcode and build and run. After the splash screen intro, you should see the following screen appear on your device or your simulator:

space_invaders_first_run

Creepy – the invaders are watching you! However, if you see the screen above, this means you’re ready to get started.

Adding Colorful Invaders

All right, time to make some invaders! In this game, you’re going to create three types of invaders, so open GameScene.swift and add this enumeration inside the GameScene class, right after the line var contentCreated = false:

enum InvaderType {
  case A
  case B
  case C
 
  static var size: CGSize {
    return CGSize(width: 24, height: 16)
  }
 
  static var name: String {
    return "invader"
  }
}

Here you create an enumeration with three different cases, and a few helper properties to return the size of the invader sprite, and a description.

Next, add this new method directly after createContent():

func makeInvaderOfType(invaderType: InvaderType) -> SKNode {
  // 1
  var invaderColor: SKColor
 
  switch(invaderType) {
  case .A:
    invaderColor = SKColor.redColor()
  case .B:
    invaderColor = SKColor.greenColor()
  case .C:
    invaderColor = SKColor.blueColor()
  }
 
  // 2
  let invader = SKSpriteNode(color: invaderColor, size: InvaderType.size)
  invader.name = InvaderType.name
 
  return invader
}

You take the following actions in the above code:

  1. Use the invaderType parameter to determine the color of the invader.
  2. Call the handy convenience initializer SKSpriteNode(color:size:) to initialize a sprite that renders as a rectangle of the given color invaderColor with the enumeration’s size InvaderType.size.

Okay, so a colored block is not the most menacing enemy imaginable. It may be tempting to design invader sprite images and dream about all the cool ways you can animate them, but the best approach is to focus on the game logic first, and worry about aesthetics later.

Adding makeInvaderOfType() isn’t quite enough to display the invaders on the screen. You’ll need something to invoke this method and place the newly created sprites in the scene.

First, you’ll need a few constants. Add the following constants inside GameScene, right after the declaration of InvaderType:

let kInvaderGridSpacing = CGSize(width: 12, height: 12)
let kInvaderRowCount = 6
let kInvaderColCount = 6

These are some constants to represent how you’ll be laying out the invaders in this game – basically a 6×6 grid, with 12×12 point spacing in-between each invader.

Next add the following method directly after makeInvaderOfType():

func setupInvaders() {
  // 1
  let baseOrigin = CGPoint(x: size.width / 3, y: size.height / 2)
 
  for row in 0..<kInvaderRowCount {
    // 2
    var invaderType: InvaderType
 
    if row % 3 == 0 {
      invaderType = .A
    } else if row % 3 == 1 {
      invaderType = .B
    } else {
      invaderType = .C
    }
 
    // 3
    let invaderPositionY = CGFloat(row) * (InvaderType.size.height * 2) + baseOrigin.y
 
    var invaderPosition = CGPoint(x: baseOrigin.x, y: invaderPositionY)
 
    // 4
    for _ in 1..<kInvaderRowCount {
      // 5
      let invader = makeInvaderOfType(invaderType)
      invader.position = invaderPosition
 
      addChild(invader)
 
      invaderPosition = CGPoint(
        x: invaderPosition.x + InvaderType.size.width + kInvaderGridSpacing.width,
        y: invaderPositionY
      )
    }
  }
}

The above method lays out invaders in a grid of rows and columns. Each row contains only a single type of invader. The logic looks complicated, but if you break it down, it makes perfect sense:

  1. Declare and set the baseOrigin constant (representing the origin of where to start spawning areas – 1/3 from the right of the screen, and 1/2 from the bottom of the screen) and loop over the rows.
  2. Choose a single InvaderType for all invaders in this row based on the row number.
  3. Do some math to figure out where the first invader in this row should be positioned.
  4. Loop over the columns.
  5. Create an invader for the current row and column and add it to the scene.
  6. Update the invaderPosition so that it’s correct for the next invader.

Now, you just need to display the invaders on the screen. Replace the temporary invader setup code in createContent() with setupInvaders() just above the background color:

setupInvaders()

Build and run your app; you should see a bunch of invaders on the screen, as shown below:

space_invaders_added_color

The rectangular alien overlords are here! :]

Create Your Valiant Ship

With those evil invaders on screen, your mighty ship can’t be far behind. Just as you did for the invaders, you first need to define a few constants.

Add the following code immediately below the kInvaderColCount line:

let kShipSize = CGSize(width: 30, height: 16)
let kShipName = "ship"

kShipSize stores the size of the ship, and kShipName stores the name you will set on the sprite node, so you can easily look it up later.

Next, add the following two methods just after setupInvaders():

func setupShip() {
  // 1
  let ship = makeShip()
 
  // 2
  ship.position = CGPoint(x: size.width / 2.0, y: kShipSize.height / 2.0)
  addChild(ship)
}
 
func makeShip() -> SKNode {
  let ship = SKSpriteNode(color: SKColor.greenColor(), size: kShipSize)
  ship.name = kShipName
  return ship
}

Here’s the interesting bits of logic in the two methods above:

  1. Create a ship using makeShip(). You can easily reuse makeShip() later if you need to create another ship (e.g. if the current ship gets destroyed by an invader and the player has “lives” left).
  2. Place the ship on the screen. In Sprite Kit, the origin is at the lower left corner of the screen. The anchorPoint is based on a unit square with (0, 0) at the lower left of the sprite’s area and (1, 1) at its top right. Since SKSpriteNode has a default anchorPoint of (0.5, 0.5), i.e., its center, the ship’s position is the position of its center. Positioning the ship at kShipSize.height / 2.0 means that half of the ship’s height will protrude below its position and half above. If you check the math, you’ll see that the ship’s bottom aligns exactly with the bottom of the scene.

To display your ship on the screen, add the following line below setupInvaders() in createContent():

setupShip()

Build and run your app; and you should see your ship arrive on the scene, as below:

space_invaders_added_player

Fear not, citizens of Earth! Your trusty spaceship is here to save the day!

Adding the Heads Up Display (HUD)

It wouldn’t be much fun to play Space Invaders if you didn’t keep score, would it? You’re going to add a heads-up display (or HUD) to your game. As a star pilot defending Earth, your performance is being monitored by your commanding officers. They’re interested in both your “kills” (score) and “battle readiness” (health).

Add the following constants at the top of GameScene.swift, just below kShipName:

let kScoreHudName = "scoreHud"
let kHealthHudName = "healthHud"

Now, add your HUD by inserting the following method right after makeShip():

func setupHud() {
  // 1
  let scoreLabel = SKLabelNode(fontNamed: "Courier")
  scoreLabel.name = kScoreHudName
  scoreLabel.fontSize = 25
 
  // 2
  scoreLabel.fontColor = SKColor.greenColor()
  scoreLabel.text = String(format: "Score: %04u", 0)
 
  // 3
  scoreLabel.position = CGPoint(
    x: frame.size.width / 2,
    y: size.height - (40 + scoreLabel.frame.size.height/2)
  )
  addChild(scoreLabel)
 
  // 4
  let healthLabel = SKLabelNode(fontNamed: "Courier")
  healthLabel.name = kHealthHudName
  healthLabel.fontSize = 25
 
  // 5
  healthLabel.fontColor = SKColor.redColor()
  healthLabel.text = String(format: "Health: %.1f%%", 100.0)
 
  // 6
  healthLabel.position = CGPoint(
    x: frame.size.width / 2,
    y: size.height - (80 + healthLabel.frame.size.height/2)
  )
  addChild(healthLabel)
}

This is boilerplate code for creating and adding text labels to a scene. The relevant bits are as follows:

  1. Give the score label a name so you can find it later when you need to update the displayed score.
  2. Color the score label green.
  3. Position the score label.
  4. Give the health label a name so you can reference it later when you need to update the displayed health.
  5. Color the health label red; the red and green indicators are common colors for these indicators in games, and they’re easy to differentiate in the middle of furious gameplay.
  6. Position the health below the score label.

Add the following line below setupShip() in createContent() to call the setup method for your HUD:

setupHud()

Build and run your app; you should see the HUD in all of its red and green glory on your screen as shown below:

space_invaders_hud

Invaders? Check. Ship? Check. HUD? Check. Now all you need is a little dynamic action to tie it all together!

Adding Motion to the Invaders

To render your game onto the screen, Sprite Kit uses a game loop which searches endlessly for state changes that require on-screen elements to be updated. The game loop does several things, but you’ll be interested in the mechanisms that update your scene. You do this by overriding the update() method, which you’ll find as a stub in your GameScene.swift file.

When your game is running smoothly and renders 60 frames-per-second (iOS devices are hardware-locked to a max of 60 fps), update() will be called 60 times per second. This is where you modify the state of your scene, such as altering scores, removing dead invader sprites, or moving your ship around…

You’ll use update() to make your invaders move across and down the screen. Each time Sprite Kit invokes update(), it’s asking you “Did your scene change?”, “Did your scene change?”… It’s your job to answer that question — and you’ll write some code to do just that.

Insert the following code at the top of GameScene.swift, just above the definition of the InvaderType enum:

enum InvaderMovementDirection {
  case Right
  case Left
  case DownThenRight
  case DownThenLeft
  case None
}

Invaders move in a fixed pattern: right, right, down, left, left, down, right, right, … so you’ll use the InvaderMovementDirection type to track the invaders’ progress through this pattern. For example, InvaderMovementDirection.Right means the invaders are in the right, right portion of their pattern.

Next, insert the following properties just below the existing property for contentCreated:

// 1
var invaderMovementDirection: InvaderMovementDirection = .Right
// 2
var timeOfLastMove: CFTimeInterval = 0.0
// 3
let timePerMove: CFTimeInterval = 1.0

This setup code initializes invader movement as follows:

  1. Invaders begin by moving to the right.
  2. Invaders haven’t moved yet, so set the time to zero.
  3. Invaders take 1 second for each move. Each step left, right or down takes 1 second.

Now, you’re ready to make the invaders move. Add the following code just below // Scene Update:

func moveInvadersForUpdate(currentTime: CFTimeInterval) {
  // 1
  if (currentTime - timeOfLastMove < timePerMove) {
    return
  }
 
  // 2
  enumerateChildNodesWithName(InvaderType.name) {
    node, stop in
 
    switch self.invaderMovementDirection {
    case .Right:
      node.position = CGPointMake(node.position.x + 10, node.position.y)
    case .Left:
      node.position = CGPointMake(node.position.x - 10, node.position.y)
    case .DownThenLeft, .DownThenRight:
      node.position = CGPointMake(node.position.x, node.position.y - 10)
    case .None:
      break
    }
 
    // 3
    self.timeOfLastMove = currentTime
  }
}

Here’s a breakdown of the code above, comment by comment:

  1. If it’s not yet time to move, then exit the method. moveInvadersForUpdate() is invoked 60 times per second, but you don’t want the invaders to move that often since the movement would be too fast for a normal person to see.
  2. Recall that your scene holds all of the invaders as child nodes; you added them to the scene using addChild() in setupInvaders() identifying each invader by its name property. Invoking enumerateChildNodesWithName() only loops over the invaders because they’re named kInvaderName; this makes the loop skip your ship and the HUDs. The guts of the block moves the invaders 10 pixels either right, left or down depending on the value of invaderMovementDirection.
  3. Record that you just moved the invaders, so that the next time this method is invoked (1/60th of a second from now), the invaders won’t move again till the set time period of one second has elapsed.

To make your invaders move, add the following to update():

moveInvadersForUpdate(currentTime)

Build and run your app; you should see your invaders slowly walk their way to the right:

space_invaders_movement

Hmmm, what happened? Why did the invaders disappear? Maybe the invaders aren’t as menacing as you thought!

The invaders don’t yet know that they need to move down and change their direction once they hit the side of the playing field. Guess you’ll need to help those invaders find their way!

Controlling the Invaders’ Direction

Adding the following code just after // Invader Movement Helpers:

func determineInvaderMovementDirection() {
  // 1
  var proposedMovementDirection: InvaderMovementDirection = invaderMovementDirection
 
  // 2
  enumerateChildNodesWithName(InvaderType.name) {
    node, stop in
 
    switch self.invaderMovementDirection {
    case .Right:
      //3
      if (CGRectGetMaxX(node.frame) >= node.scene!.size.width - 1.0) {
        proposedMovementDirection = .DownThenLeft
 
        stop.memory = true
      }
    case .Left:
      //4
      if (CGRectGetMinX(node.frame) <= 1.0) {
        proposedMovementDirection = .DownThenRight
 
        stop.memory = true
      }
 
    case .DownThenLeft:
      proposedMovementDirection = .Left
 
      stop.memory = true
 
    case .DownThenRight:
      proposedMovementDirection = .Right
 
      stop.memory = true
 
    default:
      break
    }
 
  }
 
  //7
  if (proposedMovementDirection != invaderMovementDirection) {
    invaderMovementDirection = proposedMovementDirection
  }
}

Here’s what’s going on in the above code:

  1. Here you keep a reference to the current invaderMovementDirection so that you can modify it in //2.
  2. Loop over all the invaders in the scene and invoke the block with the invader as an argument.
  3. If the invader’s right edge is within 1 point of the right edge of the scene, it’s about to move offscreen. Set proposedMovementDirection so that the invaders move down then left. You compare the invader’s frame (the frame that contains its content in the scene’s coordinate system) with the scene width. Since the scene has an anchorPoint of (0, 0) by default, and is scaled to fill its parent view, this comparison ensures you’re testing against the view’s edges.
  4. If the invader’s left edge is within 1 point of the left edge of the scene, it’s about to move offscreen. Set proposedMovementDirection so that invaders move down then right.
  5. If invaders are moving down then left, they’ve already moved down at this point, so they should now move left. How this works will become more obvious when you integrate determineInvaderMovementDirection with moveInvadersForUpdate().
  6. If the invaders are moving down then right, they’ve already moved down at this point, so they should now move right.
  7. If the proposed invader movement direction is different than the current invader movement direction, update the current direction to the proposed direction.

Add the following code within moveInvadersForUpdate(), immediately after the conditional check of timeOfLastMove:

determineInvaderMovementDirection()

Why is it important that you add the invocation of determineInvaderMovementDirection() only after the check on timeOfLastMove? That’s because you want the invader movement direction to change only when the invaders are actually moving. Invaders only move when the check on timeOfLastMove passes — i.e., the conditional expression is true.

What would happen if you added the new line of code above as the very first line of code in moveInvadersForUpdate(currentTime: CFTimeInterval)? If you did that, then there would be two bugs:

  • You’d be trying to update the movement direction way too often — 60 times per second — when you know it can only change at most once per second.
  • The invaders would never move down, as the state transition from DownThenLeft to Left would occur without an invader movement in between. The next invocation of moveInvadersForUpdate() that passed the check on timeOfLastMove would be executed with Left and would keep moving the invaders left, skipping the down move. A similar bug would exist for DownThenRight and Right.

Build and run your app; you’ll see the invaders moving as expected across and down the screen:

space_invaders_invader_direction

Note: You might have noticed that the invaders’ movement is jerky. That’s a consequence of your code only moving invaders once per second — and moving them a decent distance at that. But the movement in the original game was jerky, so keeping this feature helps your game seem more authentic.

Controlling Ship Movements with Device Motion

You might be familiar with UIAccelerometer, which has been available since iOS 2.0 for detecting device tilt. However, UIAccelerometer was deprecated in iOS 5.0, so iOS 9 apps should use CMMotionManager, which is part of Apple’s CoreMotion framework.

The CoreMotion library has already been added to the starter project, so there’s no need for you to add it.

Your code can retrieve accelerometer data from CMMotionManager in two different ways:

  1. Pushing accelerometer data to your code: In this scenario, you provide CMMotionManager with a block that it calls regularly with accelerometer data. This doesn’t fit well with your scene’s update() method that ticks at regular intervals of 1/60th of a second. You only want to sample accelerometer data during those ticks — and those ticks likely won’t line up with the moment that CMMotionManager decides to push data to your code.
  2. Pulling accelerometer data from your code: In this scenario, you call CMMotionManager and ask it for data when you need it. Placing these calls inside your scene’s update() method aligns nicely with the ticks of your system. You’ll be sampling accelerometer data 60 times per second, so there’s no need to worry about lag.

Your app should only use a single instance of CMMotionManager to ensure you get the most reliable data. To that effect, declare and initialize the following property at the top of GameScene:

let motionManager: CMMotionManager = CMMotionManager()

Now, add the following code to didMoveToView(), right after the contentCreated = true line:

motionManager.startAccelerometerUpdates()

This new code kicks off the production of accelerometer data. At this point, you can use the motion manager and its accelerometer data to control your ship’s movement.

Add the following method just below moveInvadersForUpdate():

func processUserMotionForUpdate(currentTime: CFTimeInterval) {
  // 1
  if let ship = childNodeWithName(kShipName) as? SKSpriteNode {
    // 2
    if let data = motionManager.accelerometerData {
      // 3
      if fabs(data.acceleration.x) > 0.2 {
        // 4 How do you move the ship?
        print("Acceleration: \(data.acceleration.x)")
      }
    }
  }
}

Dissecting this method, you’ll find the following:

  1. Get the ship from the scene so you can move it.
  2. Get the accelerometer data from the motion manager. It is an Optional, that is a variable that can hold either a value or no value. The if let data statement allows to check if there is a value in accelerometerData, if is the case assign it to the constant data in order to use it safely within the if’s scope.
  3. If your device is oriented with the screen facing up and the home button at the bottom, then tilting the device to the right produces data.acceleration.x > 0, whereas tilting it to the left produces data.acceleration.x < 0. The check against 0.2 means that the device will be considered perfectly flat/no thrust (technically data.acceleration.x == 0) as long as it's close enough to zero (data.acceleration.x in the range [-0.2, 0.2]). There's nothing special about 0.2, it just seemed to work well for me. Little tricks like this will make your control system more reliable and less frustrating for users.
  4. Hmmm, how do you actually use data.acceleration.x to move the ship? You want small values to move the ship a little and large values to move the ship a lot. For now, you just print out the acceleration value.

Finally, add the following line to the top of update():

processUserMotionForUpdate(currentTime)

Your new processUserMotionForUpdate now gets called 60 times per second as the scene updates.

Build and run - but this time, be sure that you run on a physical device like an iPhone. You won't be able to test the tilt code unless you are running the game on an actual device.

As you tilt your device, the ship won't move - however you will see some print statements in your console log like this:

Acceleration: 0.280059814453125
Acceleration: 0.255386352539062
Acceleration: 0.227584838867188
Acceleration: -0.201553344726562
Acceleration: -0.2618408203125
Acceleration: -0.280426025390625
Acceleration: -0.28662109375

Here you can see the acceleration changing as you tilt the device back and forth. Next, let's use this value to make the ship move - through the power of Sprite Kit physics!

Translating Motion Controls into Movement via Physics

Sprite Kit has a powerful built-in physics system based on Box 2D that can simulate a wide range of physics like forces, translation, rotation, collisions, and contact detection. Each SKNode, and thus each SKScene and SKSpriteNode, has an SKPhysicsBody attached to it. This SKPhysicsBody represents the node in the physics simulation.

Add the following code right before the final return ship line in makeShip():

// 1
ship.physicsBody = SKPhysicsBody(rectangleOfSize: ship.frame.size)
 
// 2
ship.physicsBody!.dynamic = true
 
// 3
ship.physicsBody!.affectedByGravity = false
 
// 4
ship.physicsBody!.mass = 0.02

Taking each comment in turn, you'll see the following:

  1. Create a rectangular physics body the same size as the ship.
  2. Make the shape dynamic; this makes it subject to things such as collisions and other outside forces.
  3. You don't want the ship to drop off the bottom of the screen, so you indicate that it's not affected by gravity.
  4. Give the ship an arbitrary mass so that its movement feels natural.

Now replace the println statement in processUserMotionForUpdate (right after comment // 4) with the following:

ship.physicsBody!.applyForce(CGVectorMake(40.0 * CGFloat(data.acceleration.x), 0))

The new code applies a force to the ship's physics body in the same direction as data.acceleration.x. The number 40.0 is an arbitrary value to make the ship's motion feel natural.

Build and run your game and try tilting your device left or right; Your ship will fly off the side of the screen, lost in the deep, dark reaches of space. If you tilt hard and long enough in the opposite direction, you might get your ship to come flying back the other way. But at present, the controls are way too flaky and sensitive. You'll never kill any invaders like this!

An easy and reliable way to prevent things from escaping the bounds of your screen during a physics simulation is to build what's called an edge loop around the boundary of your screen. An edge loop is a physics body that has no volume or mass but can still collide with your ship. Think of it as an infinitely-thin wall around your scene.

Since your GameScene is a kind of SKNode, you can give it its own physics body to create the edge loop.

Add the following code to createContent() right before the setupInvaders() line:

physicsBody = SKPhysicsBody(edgeLoopFromRect: frame)

The new code adds the physics body to your scene.

Build and run your game once more and try tilting your device to move your ship, as below:

space_invaders_player_movement

What do you see? If you tilt your device far enough to one side, your ship will collide with the edge of the screen. It no longer flies off the edge of the screen. Problem solved!

Depending on the ship's momentum,you may also see the ship bouncing off the edge of the screen, instead of just stopping there. This is an added bonus that comes for free from Sprite Kit's physics engine — it's a property called restitution. Not only does it look cool, but it is what's known as an affordance since bouncing the ship back towards the center of the screen clearly communicates to the user that the edge of the screen is a boundary that cannot be crossed.

Where to Go From Here?

Here is the example project for the game up to this point.

So far, you've created invaders, your ship, and a Heads Up Display (HUD) and drawn them on-screen. You've also coded logic to make the invaders move automatically and to make your ship move as you tilt your device.

In part two of this tutorial, you'll add firing actions to your ship as well as the invaders, along with some collision detection so you'll know when you've hit the invaders — and vice versa! You'll also polish your game by adding both sound effects as well as realistic images to replace the colored rectangles that currently serve as placeholders for invaders and your ship.

In the meantime, if you have any questions or comments, please feel free to join in the discussions below!

The post How To Make a Game Like Space Invaders with Sprite Kit and Swift Tutorial: Part 1 appeared first on Ray Wenderlich.


Viewing all articles
Browse latest Browse all 4387

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>