Discover millions of ebooks, audiobooks, and so much more with a free trial

From $11.99/month after trial. Cancel anytime.

Swift Game Development: Learn iOS 12 game development using SpriteKit, SceneKit and ARKit 2.0, 3rd Edition
Swift Game Development: Learn iOS 12 game development using SpriteKit, SceneKit and ARKit 2.0, 3rd Edition
Swift Game Development: Learn iOS 12 game development using SpriteKit, SceneKit and ARKit 2.0, 3rd Edition
Ebook788 pages4 hours

Swift Game Development: Learn iOS 12 game development using SpriteKit, SceneKit and ARKit 2.0, 3rd Edition

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Embrace the mobile gaming revolution by creating popular iOS games with Swift 4.2




Key Features



  • Learn to create games for iPhone and iPad with the latest Swift Programming language


  • Understand the fundamental concepts of game development like game physics, camera action, sprites, controls, among others


  • Build Augmented reality games using ARKit for true performance



Book Description



Swift is the perfect choice for game development. Developers are intrigued by Swift and want to make use of new features to develop their best games yet. Packed with best practices and easy-to-use examples, this book leads you step by step through the development of your first Swift game.






The book starts by introducing Swift's best features – including its new ones for game development. Using SpriteKit, you will learn how to animate sprites and textures. Along the way, you will master physics, animations, and collision effects and how to build the UI aspects of a game. You will then work on creating a 3D game using the SceneKit framework. Further, we will look at how to add monetization and integrate Game Center. With iOS 12, we see the introduction of ARKit 2.0. This new version allows us to integrate shared experiences such as multiplayer augmented reality and persistent AR that is tied to a specific location so that the same information can be replicated on all connected devices. In the next section, we will dive into creating Augmented Reality games using SpriteKit and SceneKit. Then, finally, we will see how to create a Multipeer AR project to connect two devices, and send and receive data back and forth between those devices in real time.






By the end of this book, you will be able to create your own iOS games using Swift and publish them on the iOS App Store.




What you will learn



  • Deliver powerful graphics, physics, and sound in your game by using SpriteKit and SceneKit


  • Set up a scene using the new capabilities of the scene editor and custom classes


  • Maximize gameplay with little-known tips and strategies for fun, repeatable action


  • Make use of animations, graphics, and particles to polish your game


  • Understand the current mobile monetization landscape


  • Integrate your game with Game Center


  • Develop 2D and 3D Augmented Reality games using Apple's new ARKit framework


  • Publish your game to the App Store



Who this book is for



If you wish to create and publish iOS games using Swift, then this book is for you. No prior game development or experience with Apple ecosystem is needed.

LanguageEnglish
Release dateSep 28, 2018
ISBN9781788472807
Swift Game Development: Learn iOS 12 game development using SpriteKit, SceneKit and ARKit 2.0, 3rd Edition

Read more from Shekar Siddharth

Related to Swift Game Development

Related ebooks

Programming For You

View More

Related articles

Reviews for Swift Game Development

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Swift Game Development - Shekar Siddharth

    (missing alt)

    Table of Contents

    Swift Game Development Third Edition

    Why subscribe?

    Packt.com

    Contributors

    About the authors

    About the reviewer

    Packt is Searching for Authors Like You

    Preface

    Who this book is for

    What this book covers

    To get the most out of this book

    Download the example code files

    Conventions used

    Get in touch

    Reviews

    1. Designing Games with Swift

    Why you will love Swift

    Prerequisites

    What you will learn in this book

    Embracing SpriteKit

    Reacting to player input

    Structuring your game code

    Building UI/menus/levels

    Integrating with Game Center

    Maximizing fun

    Crossing the finish line

    Monetizing your work

    New in Swift 4.2

    Setting up your development environment

    Introducing and installing Xcode

    Creating our first Swift game

    Navigating our project

    Exploring the SpriteKit demo

    Examining the demo code

    Cleaning up

    Summary

    2. Sprites, Camera, Action!

    Preparing your project

    Drawing your first sprite

    Building a SKSpriteNode class

    Animation—movement, scaling, and rotation

    Sequencing multiple animations

    Recapping your first sprite

    The story on positioning

    Alignment with anchor points

    Working with textures

    Downloading the free assets

    More exceptional art assets

    Drawing your first textured sprite

    Adding the bee image to your project

    Loading images with SKSpriteNode

    Designing for Retina

    The ideal asset approach

    Hands-on with retina in SpriteKit

    Organizing art into texture atlases

    Exploring Assets.xcassets

    Collecting art into texture atlases

    Updating our bee node to use the texture atlas

    Iterating through texture atlas frames

    Putting it all together

    Centering the camera on a sprite

    Summary

    3. Mix in the Physics

    Laying the foundations

    Adopting a protocol for consistency

    Organizing game objects into classes

    The icy tundra

    Adding the ground texture to Assets.xcassets

    Adding the Ground class

    Tiling a texture

    Running wire to the ground

    Adding the player's character

    Renovating the GameScene class

    Physics bodies and gravity

    Dropping like flies

    Solidifying the ground

    Exploring physics simulation mechanics

    Bumping bees into bees

    Movement with impulses and forces

    Summary

    4. Adding Controls

    Retrofitting the Player class for flight

    The Beekeeper

    Updating the Player class

    Moving the ground

    Assigning a physics body to the player

    Creating a physics body shape from a texture

    Polling for device movement with Core Motion

    Implementing the Core Motion code

    Wiring up the sprite onTap events

    Implementing touchesBegan in the GameScene

    Larger than life

    Teaching our penguin to fly

    Listening for touches in GameScene

    Fine-tuning gravity

    Spreading your wings

    Improving the camera

    Pushing Pierre forward

    Tracking the player's progress

    Looping the ground as player the moves forward

    Summary

    5. Spawning Enemies, Coins, and Power-Ups

    Introducing the cast

    Locating and adding the art assets

    Adding the Power-up Star

    Adding the Star class

    A new enemy - the Mad Fly

    Adding the MadFly class

    Another terror - Bats!

    Adding the Bat class

    Guarding the ground with the Blade

    Adding the Blade class

    Adding coins

    Creating the coin classes

    Organizing the project navigator

    Testing the new game objects

    Preparing for endless flight

    Summary

    6. Generating a Never-Ending World

    Designing levels with the SpriteKit scene editor

    Separating level data from game logic

    Using custom classes in the scene editor

    Building encounters for Pierre Penguin

    Creating our first encounter

    Integrating scenes into the game

    Looping encounters for a never-ending world

    Building more encounters

    Updating the EncounterManager class

    Storing metadata in SKSpriteNodeuserData property

    Wiring up EncounterManager in the GameScene class

    Adding the Power-up Star at random places

    Turning bronze coins into gold coins

    Summary

    7. Implementing Collision Events

    Learning the SpriteKit collision vocabulary

    Collision versus contact

    Physics category masks

    Using category masks in Swift

    Adding contact events to our game

    Setting up the physics categories

    Assigning categories to game objects

    The player

    The ground

    The Power-up Star

    Enemies

    Coins

    Preparing GameScene for contact events

    Viewing console output

    Testing our contact code

    Player health and damage

    Animations for damage and game over

    The damage animation

    The game over animation

    Collecting coins

    The Power-up Star logic

    Summary

    8. Polishing to a Shine – HUD, Parallax Backgrounds, Particles, and More

    Adding a HUD

    Implementing the HUD

    Parallax background layers

    Adding the background assets

    Implementing a background class

    Wiring up backgrounds in the GameScene class

    Using the particle system

    Adding the circle particle asset

    Creating a SpriteKit particle file

    Configuring the path particle settings

    Name

    Background

    Texture

    Emitter

    Lifetime

    Position Range

    Angle

    Speed

    Acceleration

    Alpha

    Scale

    Rotation

    Color Blend

    Color Ramp

    Adding the particle emitter to the game

    Granting safety as the game starts

    Summary

    9. Adding Menus and Sounds

    Building the main menu

    Creating the menu scene and menu nodes

    Launching the main menu when the game starts

    Wiring up the START GAME button

    Adding the restart game menu

    Extending the HUD

    Wiring up GameScene for game over

    Informing the GameScene class when the player dies

    Implementing touch events for the restart menu

    Adding music with AVAudio

    Adding sound assets to the game

    Playing background music

    Playing sound effects

    Adding the coin sound effect to the Coin class

    Adding the power-up and hurt sound effects to the Player class

    Playing sound effects with SKAction

    Adding a mute button and volume slider

    Adding Options to the Menu Scene

    Summary

    10. Standing out in the Crowd with Advanced Features

    Adding crates to smash open

    Creating the Crate particle effects

    Recycling emitter nodes with particle pools

    Wiring up crate contact events

    Creating the health power-up crate

    Spawning smashable crates that reward coins

    Summary

    11. Introduction to SceneKit

    Creating a Scene with SCNScene

    Adding objects to the scene

    Adding a sphere

    Adding light sources

    Adding a camera to the scene

    Adding a floor

    Importing scenes from an external 3D application

    Creating the hero class and physics

    Adding an enemy and collision detection

    Adding a SpriteKit overlay

    Adding labels and buttons

    Adding touch interactivity

    Adding the Gameloop

    Setting a GameOver condition

    Checking for contact

    Adding wall and floor parallax

    Adding particles

    Adding character animation

    Summary

    12. Choosing a Monetization Strategy

    Developing your marketing plan

    When to start marketing

    Marketing checklist

    Leveraging crowdfunding

    Pros and cons of crowdfunding

    Showing display ads for revenue

    The upsides to showing ads

    The downsides to showing ads

    Adding an AdMob Ad in the App

    Selling in-app purchases

    In-app purchase strategies

    A word about farming your players

    Adding In-App Purchases

    Localization in foreign markets

    Managing scope and completing projects

    Summary

    13. Integrating with Game Center

    Authenticating the player's Game Center account

    Opening Game Center in our game

    Updating the leaderboard from the code

    Adding an achievement

    Creating a new achievement in iTunes Connect

    Updating achievements from the code

    Summary

    14. Introduction to Spritekit with ARKit

    Requirements for the project

    Creating an AR Spritekit project

    Adding text and crosshair

    Adding anchors at random locations

    Adding custom sprite

    Registering touch controls to remove game objects

    Summary

    15. Introduction to Scenekit with ARKit

    Going through the basic Scenekit/ARKit project

    Project setup and detecting a plane

    Adding touches

    Adding Game Objects

    Stop detecting planes

    Adding light source

    Adding ground node

    Adding Hero and Enemy

    Adding Score and Gameover text

    Finishing touches

    Summary

    16. Publishing the Game on the App Store

    Creating the Bundle ID for the app

    Preparing the project

    Create the App in the itunesconnect portal

    Upload the App and submit for review

    Summary

    17. Multipeer Augmented Reality

    Multipeer connectivity framework overview

    Creating the multipeer session class

    Creating a UI for the app

    Setting outlets and adding variables

    Initializing the view

    Update session and tracking

    Hosting and joining the session

    Sending and receiving data

    Initializing a multipeer session

    Testing the application

    Summary

    Other Books You May Enjoy

    Leave a review – let other readers know what you think

    Index

    Swift Game Development Third Edition


    Swift Game Development Third Edition

    Copyright © 2018 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    Commissioning Editor: Ashwin Nair

    Acquisition Editor: Reshma Raman

    Content Development Editors: Flavian Vaz

    Technical Editor: Akhil Nair

    Copy Editor: Safis Editing

    Project Coordinator: Sheejal Shah

    Proofreader: Safis Editing

    Indexers: Tejal Daruwale Soni

    Graphics: Jason Monteiro

    Production Coordinator: Shantanu Zagade

    First published: July 2015

    Second published: February 2017

    Third edition: September 2018

    Production reference: 1260918

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78847-115-2

    www.packtpub.com

    Swift Game Development Third Edition

    mapt.io

    Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

    Why subscribe?

    Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

    Learn better with Skill Plans built especially for you

    Get a free eBook or video every month

    Mapt is fully searchable

    Copy and paste, print, and bookmark content

    Packt.com

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.Packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

    At www.Packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

    Contributors

    About the authors

    Siddharth Shekar is a game developer and teacher with over 5 years of industry experience and 12 years of experience in C++ and other programming languages, and is adept at graphics libraries such as OpenGL and Vulkan and game engines such as Unity and Unreal. He has also published games on the iOS and Android App Stores.

    Siddharth has also authored 4 books, including Mastering Android Game Development with Unity and Learning iOS 8 Game Development Using Swift, all published by Packt Publishing

    He currently lives in New Zealand and is a lecturer in the Games Department at Media Design School. He teaches graphics programming and PlayStation 4 native game development, and mentors final year production students.

    I would like to thank my parents for supporting me in everything that I choose to do. I would also like to thank Media Design School for encouraging me to continue working on this book. Finally, I would like to thank Packt Publishing for putting this book together and offering me the opportunity to write the book.

    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 form—an amazing combination of visual, auditory, and psychological challenges—rewarding to both the player and the creator.

    He enjoyed writing this book and sincerely hopes that it directly furthers your career or hobby.

    About the reviewer

    Rafał Sroka is a Software Engineer with extensive expertise in iOS development, building-up mobile apps, QA and release process, API design, and complex software projects. He has worked on various high-value projects in Poland, Germany, and Switzerland. He prefers working in cross-functional start-up environments where fast delivery of well-written and tested code is crucial. He holds a Master's degree in Electronics and Telecommunications. In his free time, he's a dedicated rock climber and mountaineer. He is a doer.

    Packt is Searching for Authors Like You

    If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

    Preface

    Swift is the perfect choice for game development. Developers are intrigued by Swift and want to make use of new features to develop their best games yet. Packed with best practices and easy-to-use examples, this book leads you step-by-step through the development of your first Swift game.

    The book starts by introducing Swift's newest and best features for game development. Using SpriteKit, you will learn how to animate sprites and textures. Along the way, you will master the physics, animations, collision effects and required to build the UI aspects of the game.

    You will then work on creating a 3D game using the SceneKit framework. You will see how to add monetization and integrate Game Center. Then you will dive into creating augmented reality (AR) games using SpriteKit and SceneKit.

    Finally, you will see how to create a Multipeer AR project to connect two devices and send and receive data back and forth between the devices in real time.

    By the end of this book, you will be able to create your own iOS games using Swift and publish them on the iOS App Store.

    Who this book is for

    The book is targeted at new and intermediate developers who want to update their knowledge about the changes in the new version of Swift and want to learn about the new ARKit framework for making AR games for iOS using Xcode 10.

    What this book covers

    Chapter 1, Designing Games with Swift, introduces you to the best features of Swift, outlines what is new in Swift 3, helps you set up your development environment, and launches your first SpriteKit project.

    Chapter 2, Sprites, Camera, Action!, teaches you the basics of drawing and animating with Swift. You will draw sprites, import textures into your project, and center the camera on the main character.

    Chapter 3, Mix in the Physics, covers the physics simulation fundamentals: physics bodies, impulses, forces, gravity, collisions, and more.

    Chapter 4, Adding Controls, explores the various methods of mobile game controls: device tilt and touch input. We will also improve the camera and core gameplay of our example game.

    Chapter 5, Spawning Enemies, Coins, and Power-ups, introduces the cast of characters we use in our example game and shows you how to create custom classes for each NPC type.

    Chapter 6, Generating a Never-Ending World, explores the SpriteKit scene editor, builds encounters for the example game, and creates a system to loop encounters endlessly.

    Chapter 7, Implementing Collision Events, delves into advanced physics simulation topics and adds custom events when sprites collide.

    Chapter 8, Polishing to a Shine – HUD, Parallax Backgrounds, Particles, and More, adds the extra fun that makes every game shine. In this chapter, you will learn how to create parallax backgrounds, learn about SpriteKit's particle emitters, and add a heads-up display overlay to your games.

    Chapter 9, Adding Menus and Sounds, builds a basic menu system and illustrates two methods of playing sounds in your games.

    Chapter 10, Standing Out in the Crowd with Advanced Features, shows you how to combine the techniques you have learned to build advanced gameplay systems.

    Chapter 11, Introduction to SceneKit, explains how to create a basic 3D game using the SceneKit framework.

    Chapter 12, Choosing a Monetization Strategy, outlines the strategies available to indie developers who want to make money from their games.

    Chapter 13 , Integrating with Game Center, links our example game to the Apple Game Center for leaderboards, achievements, and friendly challenges.

    Chapter 14 , Introduction to SpriteKit in ArKit, gives an introduction to how to make an AR game using Arkit and SpriteKit.

    Chapter 15 , Introduction to SceneKit in ArKit, demonstrates how to make a 3D augmented reality game using SceneKit and Arkit.

    Chapter 16, Ship It! Preparing for the App Store and Publication, covers the essentials of packaging your game and submitting it to the App Store.

    Chapter 17, Multipeer Augmented Reality, shows you how to create a multiplayer AR project to connect two devices in real time so they can send and receive data.

    To get the most out of this book

    This book uses the Xcode IDE version 10 (Swift 4.2). If you use a different version of Xcode, you will likely encounter syntax differences; Apple is constantly upgrading Swift's syntax. You can use Xcode's Edit | Convert | To Current Swift Syntax to update the code examples in this book to a newer version of Xcode.

    Visit https://developer.apple.com/xcode/to download Xcode.

    You will need an Apple developer account to integrate your apps with Game Center and submit your games to the App Store.

    To run ARKit games you will need an iPhone SE or higher, a fifth-generation iPad, or an iPad Pro. To run the Multipeer AR project you will need two devices because it can't be tested on an emulator.

    Download the example code files

    You can download the example code files for this book from your account at http://www.packt.com. If you purchased this book elsewhere, you can visit http://www.packt.com/support and register to have the files emailed directly to you.

    You can download the code files by following these steps:

    Log in or register at http://www.packt.com.

    Select the SUPPORT tab.

    Click on Code Downloads & Errata.

    Enter the name of the book in the Search box and follow the on-screen instructions.

    Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

    WinRAR / 7-Zip for Windows

    Zipeg / iZip / UnRarX for Mac

    7-Zip / PeaZip for Linux

    The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Swift-Game-Development-Third-Edition. In case there's an update to the code, it will be updated on the existing GitHub repository.

    We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

    Conventions used

    There are a number of text conventions used throughout this book.

    CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example; Locate the Enemies folder in the downloadable asset bundle.

    A block of code is set as follows:

    import SpriteKit

     

    class Coin: SKSpriteNode, GameSprite {

    var initialSize = CGSize(width: 26, height: 26)

    var textureAtlas: SKTextureAtlas =

    SKTextureAtlas(named: Environment)

    var value = 1

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    import SpriteKit

    import ARKit

     

    class Scene: SKScene {

       

     

        var crosshair: SKSpriteNode!     let scoreText = SKLabelNode(text: 00)

    Bold: Indicates a new term, an important word, or words that you see on the screen, for example, in menus or dialog boxes, also appear in the text like this. For example: Select System info from the Administration panel.

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Get in touch

    Feedback from our readers is always welcome.

    General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

    Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book we would be grateful if you would report this to us. Please visit, http://www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

    Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

    If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.

    Reviews

    Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

    For more information about Packt, please visit packt.com.

    Chapter 1. Designing Games with Swift

    Apple's newest version of its flagship programming language, Swift 4.2, is the perfect choice for game developers. As it matures, Swift is realizing its potential to be something special, a revolutionary tool for app creators. Swift is the gateway for developers to create the next big game in 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.

    Apple's website states the following:

    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 and a 3D game for iPhones and iPads. We will start with installing the necessary software, working through each layer of game development, ultimately publishing our new game to the App Store.

    We will also have some fun along the way! For the 2D game, we aim to create an endless flyer game featuring a magnificent flying penguin named Pierre. What is an endless flyer? Picture hit games such as 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.

    For the 3D game, we will be using SceneKit. Like SpriteKit, which is used to develop 2D games, SceneKit is a framework developed by Apple to make 3D games. The 3D game we will be an obstacle avoidance game, in which there will be obstacles players will have to either go under or jump over.

    In later chapters, we will see how to make augmented reality games using Apple's newest framework, ARKit. With ARKit, you can make really stunning augmented reality games. We will see see how to develop AR games using SpriteKit and SceneKit. Along with developing a 2D AR game, we will also see how to bring the SceneKit game we developed for 3D to life using the ARKit. In addition, we will also see how to create a Multipeer Augemented Reality App using ARKit and Multipeer Connectivity framework.

    My hope is that our demo project will serve as a template for your own creative tasks. Before you know it, you will be publishing your own game ideas using the techniques we explore together.

    In this chapter, we will cover the following topics:

    Why you will love Swift

    What you will learn in this book

    New in Swift 4.2

    Setting up your development environment

    Creating your first Swift game

    Exploring the SpriteKit demo

    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 have 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 (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.

    Open source: From version 2.2 onwards, Apple made Swift open source, curating it through the website www.swift.org, and launched a package manager with Swift 3. This is a welcome change, as it fosters greater community involvement and a larger ecosystem of third-party tools and add-ons. Eventually, we should see Swift migrate to new platforms.

    Prerequisites

    I will try to make this text easy to understand 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 any experience you have 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 will 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, 3D, and AR game design.

    Embracing SpriteKit

    SpriteKit is Apple's 2D game development framework and your main tool for iOS, macOS, tvOS, and watchOS 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 as we will be using it exclusively in our demo game.

    We will learn how to use SpriteKit to power the mechanics of our game in the following ways:

    Animating our player, enemies, and power-ups

    Painting and moving side-scrolling environments

    Playing sounds and music

    Applying physics such as gravity and impulses for movement

    Handling collisions between game objects

    Similar to SpriteKit, we will also look at SceneKit. In SceneKit, instead of importing images, we will be loading 3D models, placing them in the scene and creating a game around them. We will also see how to add player movement, animation, physics, controls, collision, and scoring.

    In ARKit, with 2D and 3D game demos, we will see how to take existing games and make augmented reality games out of them.

    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 reuse 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 with classes, protocols, inheritance, and composition.

    Building UI/menus/levels

    We will learn how 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

    Enjoying the preview?
    Page 1 of 1