Getting Started with SpriteKit - Jorge Jordan - E-Book

Getting Started with SpriteKit E-Book

Jorge Jordan

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Develop fun and exciting games and create amazing animations for your existing apps with SpriteKit, Apple's 2D game development framework

About This Book

  • Learn the key concepts of game development in iOS
  • Take advantage of SpriteKit to create your own games and improve your apps
  • Follow the step-by-step chapters to create a complete product ready to submit to the App Store

Who This Book Is For

Getting Started with SpriteKit is for beginner-level iOS developers who want to add an extra edge to their apps and create amazing games using SpriteKit. It doesn't matter whether you have experience in iOS development or not as this book will show you the swift tricks you can use to create games.

What You Will Learn

  • Create and configure a SpriteKit project from scratch
  • Load and manage the basic elements of games such as sprites, labels, and geometrical primitives
  • Handle touch events, detect collisions, and play sound audio files
  • Create complex elements, animate sprites, and run the parallax effect
  • Complete your games with key components such as a main menu, transitions between scenes, a tutorial, and the ability to load and save data
  • Increase the efficiency of your device using the accelerometer or by adding shaders, lights, and shadows
  • Gain complementary techniques such as creating or finding audio resources, applying SpriteKit to apps, or using third-party tools

In Detail

SpriteKit is Apple's game engine to develop native iOS games. Strongly boosted by the Apple Inc., Cupertino, it has increased in popularity since its first release. This book shows you the solutions provided by SpriteKit to help you create any 2D game you can imagine and apply them to create animations that will highlight your existing apps.

This book will give you the knowledge you need to apply SpriteKit to your existing apps or create your own games from scratch.

Throughout the book, you will develop a complete game. The beautiful designs implemented in the game in this book will easily lead you to learn the basis of 2D game development, including creating and moving sprites, and adding them to a game scene. You will also discover how to apply advanced techniques such as collision detection, action execution, playing music, or running animations to give a more professional aspect to the game. You will finish your first game by learning how to add a main menu and a tutorial, as well as saving and loading data from and to the player's device.

Finally, you will find out how to apply some mobile games techniques such as accelerometer use or touch detection.

Style and approach

Written in an informal way with plenty of illustrative screenshots, this easy-to-follow and practical guide will help you get the most from SpriteKit. The main part of the book provides step-by-step instructions to develop of a complete product, while the last chapters give you some complementary techniques than can be used in mobile 2D game development.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 232

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Getting Started with SpriteKit
Credits
About the Author
About the Reviewer
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. The First Step toward SpriteKit
Game engines
Creating a new SpriteKit project
Running the project for first time
How the default project looks like
The SKNode class
The SKNode class properties
The position property
The frame property
The zPosition property
The hidden property
An alpha property
The children node
name
userInteractionEnabled
Using SKNode to organize a scene
SKScene
The game loop
The SKScene properties
scaleMode
anchorPoint
size
backgroundColor
Your first game – InsideTheHat
Our first SKSpriteNode class
Adding a background
Working with screen resolutions
Summary
2. What Makes a Game a Game?
Handling touch events
Handling actions
Building a wall
Running through the doors
1-star challenge: an easier way to reset position
Solution
Creating loops
Installing doors into the wall
Collision management
Understanding collisions
Handling collisions
1-star challenge: check collisions accurately
Solution
Creating labels
Aligning labels
Playing some music
AVFoundation
2-star challenge: reproducing sound effects
Solution
Summary
3. Taking Games One Step Further
Extending the SKNode class
Creating a new class
Handling the behavior of custom classes
2-star challenge: colliding puppets
Solution
The parallax effect
The update method and delta times
Creating animations in SpriteKit
2-star challenge: animate collisions
Solution
Geometrical primitives
Summary
4. From Basic to Professional Games
Ending the game
3-star challenge: restarting a game
Solution
Creating a main menu
Transitions and scenes
The SKTransition class
Creating a tutorial
Updating the tutorial steps
Loading and saving data
The NSUserDefaults class
2-star challenge: completing the tutorial
Solution
The property list files
Summary
5. Utilizing the Hardware and Graphics Processor
Using the accelerometer
The CMMotionManager class
Compensating for the position of the device
Adding shaders to our game
Turning on the lights
Creating lights with the editor
Programmatically creating lights
2-star challenge: moving lights
Solution
Summary
6. Auxiliary Techniques
Creating particle systems
Creating an emitter with the editor
Creating the emitter programmatically
Combining SpriteKit and UIKit
Including UIKit in a game
Including SpriteKit in an app
Using third-party tools
Creating audio resources
Voice memos
Audacity
GarageBand
Font makers
How to find audio files
How to find images
Summary
Index

Getting Started with SpriteKit

Getting Started with SpriteKit

Copyright © 2016 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 author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.

First published: January 2016

Production reference: 1200116

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-733-8

www.packtpub.com

Credits

Author

Jorge Jordán

Reviewer

Andrew Kenady

Commissioning Editor

Amarabha Banerjee

Acquisition Editor

Prachi Bisht

Content Development Editor

Arshiya Ayaz Umer

Technical Editor

Vishal Mewada

Copy Editor

Vedangi Narvekar

Project Coordinator

Shipra Chawhan

Proofreader

Safis Editing

Indexer

Priya Sane

Graphics

Kirk D'Penha

Production Coordinator

Shantanu N. Zagade

Cover Work

Shantanu N. Zagade

About the Author

JorgeJordán is an iOS indie developer who's passionate about how things work since his childhood. This is the reason why he graduated in computer science and became a Java developer. After buying his first iPhone, he became deeply interested in its technology and spent his spare time learning how to develop apps for Apple's smartphones.

Over time, he founded www.insaneplatypusgames.com, where he tries to make his dreams and games come true. He is also a member of the tutorial team at www.raywenderlich.com.

Also, he has worked on a book titled Cocos2d Game Development Blueprints, Packt Publishing.

In his free time, he loves to play video games, play bass guitar, and watch TV series.

You can follow him on Twitter; his Twitter handle is @jjordanarenas.

I would like to thank my family, especially my mom and brother, for always believing in me. Thanks to them, I am the person that I am. I would also like to thank the people who have encouraged me unconditionally, especially Angélica, for being so patient and for her support while I was writing this book.

Thanks to José Antonio Espino (<[email protected]>) for creating all the art for this book and designing these amazing characters and content.

Also, thanks to all my friends: the canupis (especially to you, Eugenio, wherever you are), Javi Sáez, Kike, Pedro, Fanny, Guille, and Carmelo for all the laughs and the good times that we spend together.

I finally want to thank all the people from Packt Publishing for their efforts to make this book real.

About the Reviewer

Andrew Kenady is a game engineer from Kentucky. He holds a bachelor's degree in computer science from Western Kentucky University and has worked professionally in the games industry since his graduation in 2013. His published titles span multiple genres and platforms and include Battlepillars and Draw a Stickman: EPIC 2. He is currently working for NC2 Media, a Tennessee-based tech company, on new and promising confidential products for the mobile games sector.

In addition to working on this publication, Andrew has worked in the past as a reviewer for iOS Game Programming Cookbook by Bhanu Birani and Chhavi Vaishnav.

www.PacktPub.com

Support files, eBooks, discount offers, and more

For support files and downloads related to your book, please visit www.PacktPub.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.PacktPub.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.PacktPub.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.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

Preface

I think that I'm not wrong if I say that we as developers have the healthy (or unhealthy) habit of trying to decompose mentally (or even physically) everything that comes to our hands into smaller pieces to understand how it works.

In my case, I have to acknowledge that I am a video game lover and a restless developer, and every time I get a game or an app, I can't stop myself from thinking about how an animation or a particular effect is achieved.

This concern helped me learn how to develop apps and games. Thanks to this, I discovered that Apple provides a powerful set of tools that can be combined to create amazing games and stunning apps.

One of these tools is SpriteKit, a 2D game engine that is at the forefront of the frameworks that are available on the market and which can be included in any application to provide its dynamic features.

If you are reading these lines, you probably are either a game lover with a curiosity to learn how video games are developed, or you are an app developer who wants to know how the animations that you have seen in other apps or games have been created.

At this point starts a journey full of new experiences and knowledge that will satisfy all your curiosity. So take a seat, get comfortable, and start reading and enjoying.

What this book covers

This book contains six chapters that will guide you through the process of creating a video game with the tools provided by SpriteKit. At the same time, you will learn how to deal with the common difficulties that you may come across when developing games and how to apply the techniques that you learn here to give a stunning look to an app.

Chapter 1, The First Steps toward SpriteKit, covers the basics of developing a game with SpriteKit. In this chapter, you will learn what a game engine is and what a new SpriteKit project looks like. In addition to this, you will learn the purpose of the SKNode and SKScene classes and how to utilize them to add a background and a sprite into the game.

Chapter 2, What Makes a Game a Game?, shows the main techniques used in game development, such as moving sprites on the scene, detecting touches, and handling collisions. In addition to this, you will learn how to create and update labels and play music and sound effects.

Chapter 3, Taking Games One Step Further, teaches advanced techniques such us how to create complex nodes by extending the SKNode class or implement the parallax effect. You will also learn how to draw geometrical primitives and animate sprites.

Chapter 4, From Basic to Professional Games, helps us provide our game with the needed components to consider it as a finished product. You will learn how to create a Game Over condition for the game and a main menu scene from where you will learn how to transition to a tutorial that you will create for players so that they know the mechanism of the game. You will also learn how to save and load data from internal and external sources.

Chapter 5, Utilizing the Hardware and Graphics Processor, teaches you how to get the most advantage from the hardware of physical devices using the accelerometer or creating stunning visual effects by adding shaders, lights, and shadows into a game.

Chapter 6, Auxiliary Techniques, covers the development of special effects, which are also known as particle systems, and ways to combine SpriteKit with UIKit in order to create robust games and dynamic apps. You will also learn how to use third-party tools to create custom audio and fonts and find resources that can be used in games.

What you need for this book

To follow the implementation of the code provided in this book, you will need the following hardware and software:

An Intel-based Mac that runs on Mac OS X 10.10.4 or laterThe latest version of Xcode (version 7.0 at the time of writing this book)An enrollment in the iOS Developer Program if you want to test the games on a deviceAn iOS device to test games on it

You will not need a lot of experience developing with Swift or SpriteKit as the chapters will help you easily understand how to utilize the tools provided by the game development framework.

Who this book is for

If you are an iOS developer who wants to learn which tools offer the game development framework provided by Apple so that you can add an extra edge to your applications or learn how to bring to life the games that you have imagined in your mind, this book is for you. It has been written to teach the key concepts of 2D game development and ways to create 2D games using SpriteKit. This book will help you deploy framework tools to improve the visual experience of your apps.

Conventions

There are several text styles in this book that refer to different type of information. For example, you will find words referring code that will look like the following line:

There are a couple of storyboard files, namely Main and LaunchScreen, which are responsible for showing the game screen and launch image respectively.

You will find code blocks that look like this:

import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true }

If you are expected to perform some actions on specific places of the screen you will find the instructions highlighted in the following way:

To create a new SpriteKit project, we need to open Xcode and then navigate to File | New | Project….

You will find instructions specifying the exact value you have to enter in a text field that will look like the following line:

Call it Enemy and choose the folder where you want it to be saved.

Hints, tips, advices and notes will look like this:

Tip

Note that we just need to create a motion manager instance as thanks to it we can retrieve all the motion data we need.

Sometimes you are going to be challenged by me, requesting you to try to solve a particular situation. These challenges will be labeled as 1-star, 2-star or 3-star Challenge depending on the difficulty of the task, but they can be solved with the knowledge acquired along the book:

2-star challenge: colliding puppets

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/GettingStartedWithSpriteKit_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. The First Step toward SpriteKit

In 2013, Apple released SpriteKit, its 2D game engine, in order to compete with all the two-dimensional frameworks that were existing in the market and retain their developers in its own technological ecosystem. Since then, SpriteKit has become one of the most powerful tools that are used to develop 2D games for iOS. In this chapter, we will have a look at the elements that are a part of game development, and we'll study how to use them with SpriteKit.

In this chapter, we will explore the following topics:

Understanding game enginesCreating and understanding a new SpriteKit projectUnderstanding the SKNode classStudying the SKScene classHow to add a sprite and background to a scene

Game engines

I remember the time when I developed my first game using the BASIC programming language on my old Amstrad CPC. In those times, every game was hardware-specific, which means that you had to take into account every machine's low-level characteristics.

A game engine is a collection of software instructions that eases the process of game development by providing abstraction between the hardware and software layers. This way, you don't need to waste your efforts when performing important tasks, such as handling user inputs, playing sound and video, rendering images, or simulating physics.

As mentioned previously, SpriteKit is an engine developed by Apple to create games, and it's one of the most powerful tools that are used to build native 2D games for both iOS and Max OS X.

Creating a new SpriteKit project

The tool needed to develop SpriteKit games is Apple's Integrated Development Environment (IDE) Xcode, which can be found free of charge on Apple's App Store at https://itunes.apple.com/en/app/xcode/id497799835?l=en&mt=12. We are going to work with version 7.0, which is the latest at the time of writing the book, and iOS 9.

Creating a new project with Xcode is a straightforward task, but I would like to take advantage of it to help you understand how a default Xcode project looks like.

To create a new SpriteKit project, we need to open Xcode and then navigate to File | New | Project…. On the left-hand side, you will need to click on the iOS | Application Template; you will see what's shown in the following screenshot:

At this point, you will need to perform the following steps:

Select the Game template and click on Next.Set InsideTheHat as the template name. Ensure that the Swift option is chosen in the Language menu. Select SpriteKit as the Game Technology, and Universal is chosen on the Device Family menu. Leave the default configuration (checked) for Include Unit Tests and Include UI Tests before clicking on the Next button.Choose a place to save your project in and click on Create.

The first thing that you should look at is the left section, which is called Project Navigator and contains the folders, and files that will be a part of our game; this section is shown in the following screenshot:

The Project Navigator shows a tree of files and folders that represents a hierarchy that doesn't correspond with how these files are located on your hard drive. It means that, if you move some file, on the Project Navigator, it won't affect their position in Finder. However, if you move some file in Finder, the reference kept by Xcode will be broken and it won't be able to make use of it.

The yellow containers on the project navigator are called Groupsin Xcode, and they are equivalent to folders in a filesystem; as folders, the groups' responsibility is to organize all the files (images, classes, and so on) of an Xcode project.

One of the most important groups is the one called Project. It contains classes and resource files. As you can see in the preceding screenshot, a default project contains three Swift classes, namely AppDelegate, GameScene, and GameViewController, that will contain the core of the game.

Tip

Swift is Apple's programming language that was created by Apple for iOS, Mac OS X, watchOS, and Linux development. It was first released in June 2014.

There are a couple of storyboard files, namely Main and LaunchScreen, that are responsible for showing the game screen and launch image respectively. You will also see an image asset file, which will contain the images used on the game, and a plist file with the project configuration.

In addition to this, there is a file called GameScene.sks that should look pretty new to you. This file is used to build the screen in a static way, which is similar to a storyboard, that is created with Interface Builder.

Getting back to Xcode, there is another important section in the Project; it is the window at the center, which shows the configuration of the Project, as shown in the following screenshot:

In this panel, you will see three different sections, namely Identity, Deployment Info, and App Icons and Launch Images. Let's take a look at the second one first, where you can configure the following:

Deployment Target: This is the iOS version that is used to run the game. By default, 9.0 is chosen.Devices: This is the family of devices (iPhone, iPad, or both), on which we will be able to run the game. In our case, it shows Universal, which is the property that we specified when creating the project.Main Interface: This is the main storyboard file that is used to run the project.Device Orientation: This determines the different orientations that our game will be able to support. As we are going to develop a vertical game, unselect the Landscape Left and Landscape Right checkboxes, leaving just Portrait checked off.Status Bar Style: This helps us determine how we want the status bar to be shown.

The third section contains the following configuration:

App Icons Source: This comprises the asset catalog for app icons.Launch Images Source: This comprises the asset catalog for the launch image.Launch Screen File: This determines the screen shown while loading the game. If you want to avoid the launch screen that shows the copyright (such as the one that you can use to show your company's logo), choose Main.Storyboard in the drop-down menu.

After performing the aforementioned modifications, the project's properties will meet our requirements. So, let's run the project.