Home Game Development Game Development with Swift

Game Development with Swift

By Stephen Haney
books-svg-icon Book
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Designing Games with Swift
About this book
Publication date:
July 2015
Publisher
Packt
Pages
224
ISBN
9781783550531

 

Chapter 1. Designing Games with Swift

Apple's new language has arrived at the perfect time for game developers. Swift has the unique chance to be something special; a revolutionary tool for app creators. Swift is the gateway for developers to create the next big game on the Apple ecosystem. We have only started to explore the wonderful potential of mobile gaming and Swift is the modernization we need for our toolset. Swift is fast, safe, current, and attractive to developers coming from other languages. Whether you are new to the Apple world, or a seasoned veteran of Objective-C, I think you will enjoy making games with Swift.

Note

Apple's website states, "Swift is a successor to the C and Objective-C languages."

My goal in this book is to guide you step-by-step through the creation of a 2D game for iPhones and iPads. We will start with installing the necessary software, work through each layer of game development, and ultimately publish our new game to the App Store.

We will also have some fun along the way! We aim to create an endless flyer game featuring a magnificent flying penguin named Pierre. What is an endless flyer? Picture hit games like iCopter, Flappy Bird, Whale Trail, Jetpack Joyride, and many more – the list is quite long.

Endless flyer games are popular on the App Store and the genre necessitates that we cover many reusable components of 2D game design; I will show you how to modify our mechanics to create many different game styles. My hope is that our demo project will serve as a template for your own creative works. Before you know it, you will be publishing your own game ideas using the techniques we explore together.

The topics in this chapter include:

  • Why you will love Swift

  • What you will learn in this book

  • Setting up your development environment

  • Creating your first Swift game

 

Why you will love Swift


Swift, as a modern programming language, benefits from the collective experience of the programming community; it combines the best parts of other languages and avoids poor design decisions. Here are a few of my favorite Swift features.

Beautiful syntax

Swift's syntax is modern and approachable, regardless of your existing programming experience. Apple balanced syntax with structure to make Swift concise and readable.

Interoperability

Swift can plug directly into your existing projects and run side-by-side with your Objective-C code.

Strong typing

Swift is a strongly typed language. This means the compiler will catch more bugs at compile time – instead of when your users are playing your game! The compiler will expect your variables to be of a certain type (int, string, and so on) and will throw a compile-time error if you try to assign a value of a different type. While this may seem rigid if you are coming from a weakly typed language, the added structure results in safer, more reliable code.

Smart type inference

To make things easier, type inference will automatically detect the types of your variables and constants based upon their initial value. You do not need to explicitly declare a type for your variables. Swift is smart enough to infer variable types in most expressions.

Automatic memory management

As the Apple Swift developer guide states, "memory management just works in Swift." Swift uses a method called Automatic Reference Counting (you will see it referred to as ARC) to manage your game's memory usage. Besides a few edge cases, you can rely on Swift to safely clean up and turn off the lights.

An even playing field

One of my favorite things about Swift is how quickly the language is gaining mainstream adoption. We are all learning and growing together and there is a tremendous opportunity to break new ground.

 

Are there any downsides to Swift?


Swift is a very enjoyable language, but we should consider these two issues when starting a new project.

Less resources

Given Swift's age, it is certainly more difficult to find answers to common questions through Internet searches. Objective-C has many years' worth of discussion and answers on helpful forums like Stack Overflow. This issue improves every day as the Swift community continues to develop.

Operating system compatibility

Swift projects will run on iOS7 and higher, and OSX 10.9 and higher. Swift is the wrong choice if, in a rare case, you need to target a device running an older operating system.

 

Prerequisites


I will strive to make this text easy to comprehend for all skill levels:

  • I will assume you are brand new to Swift as a language

  • This book requires no prior game development experience, though it will help

  • I will assume you have a fundamental understanding of common programming concepts

 

What you will learn in this book


By the end of this book, you will be capable of creating and publishing your own iOS games. You will know how to combine the techniques we learn to create your own style of game and you will be well prepared to dive into more advanced topics with a solid foundation in 2D game design.

Embracing SpriteKit

SpriteKit is Apple's 2D game development framework and your main tool for iOS game design. SpriteKit will handle the mechanics of our graphics rendering, physics, and sound playback. As far as game development frameworks go, SpriteKit is a terrific choice. It is built and supported by Apple and thus integrates perfectly with Xcode and iOS. You will learn to be highly proficient with SpriteKit – we will use it exclusively in our demo game.

We will learn to use SpriteKit to power the mechanics of our game:

  • Animate our player, enemies, and power-ups

  • Paint and move side scrolling environments

  • Play sounds and music

  • Apply physics-like gravity and impulses for movement

  • Handle collisions between game objects

Reacting to player input

The control schemes in mobile games must be inventive. Mobile hardware forces us to simulate traditional controller inputs, such as directional pads and multiple buttons on the screen. This takes up valuable visible area and provides less precision and feedback than with physical devices. Many games operate with only a single input method; a single tap anywhere on the screen. We will learn how to make the best of mobile input and explore new forms of control by sensing device motion and tilt.

Structuring your game code

It is important to write well-structured code that is easy to re-use and modify as your game design inevitably changes. You will often find mechanical improvements as you develop and test your games and you will thank yourself for a clean working environment. Though there are many ways to approach this topic, we will explore some best practices to build an organized system.

Building UI/menus/levels

We will learn to switch between scenes in our game with a menu screen. We will cover the basics of user experience design and menu layout as we build our demo game.

Integrating with Game Center

Game Center is Apple's built in social gaming network. Your game can tie into Game Center to store and share high scores and achievements. We will learn how to register for Game Center, tie it into our code, and create a fun achievement system.

Maximizing fun

If you are like me, you will have dozens of ideas for games floating around your head. Ideas come easily but designing fun gameplay is difficult! It is common to find your ideas need gameplay enhancements once you see your design in action. We will look at how to avoid dead-ends and see your project through to the finish line. Plus, I will share my tips and tricks to ensure your game will bring joy to your players.

Crossing the finish line

Creating a game is a memory you will treasure. Sharing your hard work will only sweeten the satisfaction. Once our game is polished and ready for public consumption, we will navigate the App Store submission process together. You will finish feeling confident in your ability to create games with Swift and bring them to market in the App Store.

 

Further research


I will focus on the mechanics and programming involved in great game design for iOS. A few secondary topics are outside the scope of this book.


Marketing and monetizing your game

Successfully promoting and marketing your game is an important job, but this text focuses on game development mechanics and Swift code. If you are interested in making money from your games, I strongly advise you to research the best ways to promote yourself within the indie gaming community and to start marketing your game well before launch.

Making games specifically for the desktop on OSX

We are going to concentrate on iOS. You can use the techniques in this book for game development on OSX too, but you may need to research publishing and environmental differences.

 

Setting up your development environment


Learning a new development environment can be a roadblock. Luckily, Apple provides some excellent tools for iOS developers. We will start our journey by installing Xcode.

Introducing Xcode

Xcode is Apple's Integrated Development Environment (IDE). You will need Xcode to create your game projects, write and debug your code, and build your project for the App Store. Xcode also comes bundled with an iOS simulator to test your game on virtualized iPhones and iPads on your computer.

Note

Apple praises Xcode as "an incredibly productive environment for building amazing apps for Mac, iPhone, and iPad."

To install Xcode, search for xcode in the App Store or visit http://developer.apple.com and click on the Xcode icon. Please note the version of Xcode you are installing. At the time of writing, the current version of Xcode is 6.3.2. Swift is continually evolving and each new Xcode release brings syntax changes to Swift. For the best experience with the code in this book, use Xcode 6.3.x (with Swift version 1.2).

Note

Apple announced Xcode 7 and Swift 2 at WWDC 2015, but it is still in Beta at the time of writing. It looks like there will be some minor syntax changes. The knowledge and techniques in this book will still apply.

Xcode performs common IDE features to help you write better, faster code. If you have used IDEs in the past, then you are probably familiar with auto-completion, live error highlighting, running and debugging a project, and using a project manager pane to create and organize your files. However, any new program can seem overwhelming at first. We will walk through some common interface functions over the next few pages. I have also found tutorial videos on YouTube to be particularly helpful if you are stuck.

 

Creating our first Swift game


Do you have Xcode installed? Let's cut to the chase and see some game code in action in the simulator!

  1. We will need to create a new project. Launch Xcode and navigate to File | New | Project. You will see a screen asking you to select a template for your new project. Select iOS | Application in the left pane, and Game in the right pane. It should look like this:

  2. Once you select Game, click Next. The following screen asks us to enter some basic information about our project. Do not worry; we are almost at the fun bit. For our demo game, we will create a side-scrolling endless flyer featuring an astonishing flying penguin named Pierre. I am going to name this game Pierre Penguin Escapes the Antarctic, but feel free to name your project whatever you like. For now, the names are not important. You will want to pick a meaningful Product Name and Organization Identifier when you create your own game for publication. By convention, your Organization Identifier should follow a reverse domain name style. I will use com.ThinkingSwiftly, as shown in the following screenshot.

  3. After you fill out the name fields, make sure to select Swift for the Language, SpriteKit for Game Technology, and Universal for Devices. Here are my settings:

  4. Click Next and you will see the final dialog box. Save your new project. Pick a location on your computer and click Next. And we are in! Xcode has prepopulated our project with a basic SpriteKit template.

Navigating our project

Now that we have created our project, you will see the project navigator on the left-hand side of Xcode. You will use the project navigator to add, remove, and rename files and generally organize your project. You might notice that Xcode has created quite a few files in our new project. We will take it slow; do not feel pressure to know what each file does yet, but feel free to explore them if you are curious:

Exploring the SpriteKit Demo

Use the project navigator to open up the file named GameScene.swift. Xcode created GameScene.swift to store the default scene of our new game.

What is a scene? SpriteKit uses the concept of scenes to encapsulate each unique area of a game. Think of the scenes in a movie; we will create a scene for the main menu, a scene for the game over screen, a scene for each level in our game, and so on. If you are on the main menu of a game and you tap "play", you move from the menu scene to the level 1 scene.

Tip

SpriteKit prepends its class names with the letters "SK"; consequently, the scene class is SKScene.

You will see there is already some code in this scene. The SpriteKit project template comes with a very small demo. Let's take a quick look at this demo code and use it to test the iOS simulator.

Note

Please do not be concerned with understanding the demo code at this point. Your focus should be on learning the development environment.

Look for the run toolbar at the top of the Xcode window. It should look something like this:

Select the iOS device of your preference to simulate using the dropdown on the far right. Which iOS device should you simulate? You are free to use the device of your choice. I will be using an iPhone 6 for the screenshots in this book, so choose iPhone 6 if you want your results to match my images perfectly.

Note

Unfortunately, expect your game to play poorly in the simulator. SpriteKit suffers poor FPS in the iOS simulator. Once our game becomes relatively complex, we will see our FPS drop, even on high-end computers. The simulator will get you through, but it is best if you can plug in a physical device to test.

It is time for our first glimpse of SpriteKit in action! Press the gray play arrow (handy run keyboard shortcut: command + r). Xcode will build the project and launch the simulator. The simulator starts in a new window, so make sure you bring it to the front. You should see a gray background with chalky white text: Hello, World. Click around on the gray background.

You will see spinning fighter jets spawning wherever you click:

I may have gone slightly overboard with the jets . . .

If you have made it this far, congratulations! You have successfully installed and configured everything you need to make your first Swift game.

Once you have spawned a sufficient number of jets, you can close the simulator down and return to Xcode. Note: you can use the keyboard command command + q to exit the simulator or press the stop button inside Xcode. If you use the stop button, the simulator will remain open and launch your next build faster.

Examining the demo code

Let's quickly explore the demo code. Do not worry about understanding everything just yet; we will cover each element in depth later. At this point, I am hoping you will acclimatize to the development environment and pick up a few things along the way. If you are stuck, keep going! Things will actually get simpler in the next chapter, after we clear away the SpriteKit demo and start on our own game.

Make sure you have GameScene.swift open in Xcode.

The GameScene class implements three functions. Let's examine these functions. Feel free to read the code inside each function, but I do not expect you to understand the specific code just yet.

  1. The game invokes the didMoveToView function whenever it switches to the GameScene. You can think of it a bit like an initialize, or main, function for the scene. The SpriteKit demo uses it to draw the Hello World text to the screen.

  2. The touchesBegan function handles the user's touch input to the iOS device screen. The SpriteKit demo uses this function to spawn the fighter jet graphic and set it spinning wherever we touch the screen.

  3. The update function runs once for every frame drawn to the screen. The SpriteKit demo does not use this function, but we may have reason to implement it later.

Cleaning up

I hope that you have absorbed some Swift syntax and gained an overview of Swift and SpriteKit. It is time to make room for our own game; let us clear all of that demo code out! We want to keep a little bit of the boilerplate, but we can delete most of what is inside the functions. To be clear, I do not expect you to understand this code yet. This is simply a necessary step towards the start of our journey! Please remove lines from your GameScene.swift file until it looks like the following code:

import SpriteKit

class GameScene: SKScene {
  override func didMoveToView(view: SKView) {
  }
}

Once your GameScene.swift looks like the preceding code, you are ready to move on to Chapter 2, Sprites, Camera, Actions! Now the real fun begins!

 

Summary


You have already accomplished a lot. You gained your first experience with Swift, installed and configured your development environment, launched code successfully into the iOS simulator, and prepared your project for the first steps towards your own game. Great work!

We have seen enough of the "Hello World" demo – are you ready to draw your own graphics to the game screen? We will make use of sprites, textures, colors, and animation in Chapter 2, Sprites, Camera, Actions!

About the Author
  • Stephen Haney

    Stephen Haney has written two books on iOS game development. He began his programming journey at the age of 8 years on a dusty, ancient laptop using BASIC. He has been fascinated with building software and games ever since. Now well versed in multiple languages, he enjoys programming as a creative outlet the most. He believes that indie game development is an art forman amazing combination of visual, auditory, and psychological challengesrewarding to both the player and the creator. He enjoyed writing this book and sincerely hopes that it directly furthers your career or hobby.

    Browse publications by this author
Latest Reviews (5 reviews total)
The only negative point: it needs a new edition to cover Xcode 7 and Swift 2, and very soon also for Xcode 8 and Swift 3. But it's still a very good book to get you started with SpriteKit.
Game Development with Swift
Unlock this book and the full library FREE for 7 days
Start now