Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf ·...

56
Institutionen för datavetenskap Department of Computer and Information Science Final thesis Evaluation of Sprite Kit for iOS game development by Amaru Ubillus LIU-IDA/LITH-EX-A--14/061--SE 2014-11-28 Linköpings universitet SE-581 83 Linköping, Sweden Linköpings universitet 581 83 Linköping

Transcript of Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf ·...

Page 1: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Institutionen för datavetenskap Department of Computer and Information Science

Final thesis

Evaluation of Sprite Kit for iOS game development

by

Amaru Ubillus

LIU-IDA/LITH-EX-A--14/061--SE

2014-11-28

Linköpings universitet

SE-581 83 Linköping, Sweden Linköpings universitet

581 83 Linköping

Page 2: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Linköping university Department of Computer and Information Science

Final thesis

Evaluation of Sprite Kit for iOS game development

by

Amaru Ubillus

LIU-IDA/LITH-EX-A--14/061--SE

2014-11-28

Supervisor: Anders Fröberg Examinator: Erik Berglund

Page 3: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Abstract

The purpose with this thesis is to investigate whether Sprite Kit is a good toolto simplify the development process for game developers when making 2D gamesfor mobile devices. To answer this question a simple turn based strategy gamehas been developed with Sprite Kit. Sprite Kit is a game engine for making 2Dgames released by Apple.

Based on the experience I got during the development I will go through anddiscuss some of the most important tools provided by the game engine and howthey helped us to complete our game.

The conclusions I reached after making a game with Sprite Kit is that the frame-work provides all the tools necessary for creating a simple 2D mobile game foriOS. Sprite Kit hides much of the lower level details and gives the game de-veloper comprehensive development support. This helps the game developer tosave a lot of time and focus more on the gameplay when creating a game.

Page 4: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Contents

1 Introduction 11.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.3 Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.4 Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.5 Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.6 Literature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.7 Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

2 Theoretical Background 42.1 Why to use a game engine? . . . . . . . . . . . . . . . . . . . . . 42.2 iOS game development: a history . . . . . . . . . . . . . . . . . . 52.3 Introduction to Sprite Kit . . . . . . . . . . . . . . . . . . . . . . 5

2.3.1 The game loop . . . . . . . . . . . . . . . . . . . . . . . . 62.4 Sprite Kit basics . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.4.1 SKScene . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.4.2 Sprite Kit nodes . . . . . . . . . . . . . . . . . . . . . . . 82.4.3 SKActions . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.4.4 Particle emitter editor . . . . . . . . . . . . . . . . . . . . 102.4.5 Physics engine . . . . . . . . . . . . . . . . . . . . . . . . 112.4.6 Texture atlases . . . . . . . . . . . . . . . . . . . . . . . . 11

2.5 Game engine requirements . . . . . . . . . . . . . . . . . . . . . . 122.5.1 Why we chose Sprite Kit . . . . . . . . . . . . . . . . . . 13

3 Introduction to the game 143.1 A turn based strategy game . . . . . . . . . . . . . . . . . . . . . 143.2 The structure of the game . . . . . . . . . . . . . . . . . . . . . . 14

4 Programming using Sprite Kit 184.1 Scene management . . . . . . . . . . . . . . . . . . . . . . . . . . 184.2 Rendering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

4.2.1 Adding a sprite using OpenGL ES and GLKit . . . . . . 214.2.2 Adding a sprite using Sprite Kit . . . . . . . . . . . . . . 26

4.3 HUD rendering . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

Page 5: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

4.4 Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304.5 Texture Atlases and Animations . . . . . . . . . . . . . . . . . . 324.6 Physics systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374.7 Special effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

5 Result 43

6 Discussion 46

7 Conclusion 48

Page 6: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Chapter 1

Introduction

1.1 Background

Today most of the games for mobiles are developed using an already existinggame engine. Software tools are an important part of modern game developmentand improve the efficiency of making games by comprehensive development sup-port. There are a lot of different game engines to choose from when developinga game for iOS. Which game engine to choose for the next project can be adifficult choice and depends on many different factors.

Not long ago Sprite Kit was announced as Apple’s rendering engine for gamesalong with iOS 7 at the past Worldwide Developers Conference (WWDC) onJune 10-14, 2013 [1]. Sprite Kit is a graphics framework based on ObjectiveC for developing all sorts of 2D games for iOS and OS X. It comes with muchfunctionality that is useful for games, including rendering sprites on the graph-ics hardware, support for basic sound playback, physics simulation, animationsand many other features.

As a student at Linkoping University I have studied many programming coursesand have now decided to start develop my own game together with a friend. Theplan is to make an attractive 2D multiplayer strategy game and later even launchthe game on the App Store. Sprite Kit is planed to be used as the game enginefor our game.

1.2 Purpose

The aim for this report is to investigate Sprite Kit, and how the game engine canbe used to simplify the development process for developers. What tools doesthe framework provide and in which way does the tools help the programmerto more easily create games? What are the benefits of using Sprite Kit in termsof time saved and code complexity? The main technologies commonly included

1

Page 7: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

in mobile game engines to be discussed in this thesis is:

• Scene management

• Rendering

• HUD Rendering

• Actions

• Texture atlases and animations

• Physics systems

• Special effects

Each of these technologies will be explained and discussed more in detail in thefollowing sections.

1.3 Problem

There are a lot of game engines to choose from when developing a game andto find one that suits all the requirements for a specific game can be a hardmatch. Sometimes it can be even better to build your own game engine if youhave special needs. This report present a game engine used for developing 2Dmobile games for iOS and OS X.

1.4 Method

A game targeting iPhones and iPads will be implemented from scratch usingSprite Kit as the game engine. My personal experience working with the gameengine will be documented and analyzed unrelated to other game engines. Ex-perience will be obtained trough development and literature and a subjectiveview on the workflow and programming with Sprite Kit will be presented.

1.5 Limitations

This report will entirely be focusing on Sprite Kit and no other game engines orthird-party applications will be compared to Sprite Kit or taken into account.Also the implementation of the game must be delimited to the time for themaster thesis. The goal is to have an almost complete game created with SpriteKit at the time when the work is finished. To achieve this all the desiredfunctionality can not be implemented straight away. It is important to keep thegame simple and clean in the beginning and make room for further developmentaccording to time.

2

Page 8: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

1.6 Literature

The literature is collected from articles containing people’s opinions about SpriteKit in the game community and from Apples official documentation about SpriteKit. Some of the literature is also taken from ACM and IEEE, from research onmobile game engines and what game developer expect and need when developingtheir games. Finally the book ”iOS Games by tutorials” by Ray Wenderlich isused as an reference. The chosen literature is shown at the Bibliography and isthe foundation for the report.

1.7 Structure

Chapter 1: Introduction - This chapter presents the background and thepurpose of the thesis. The problem and the approach are also described as wellas the limitations that have been done.

Chapter 2: Theoretical Background - In this chapter the reader is given atheoretical background for help in understanding certain concepts. The readerwill also get a better understanding of Sprite Kit, how it works and what it offers.

Chapter 3: Introduction to the game - In this chapter a brief descrip-tion of our implemented game will be presented. What type of game it is andhow it is structured.

Chapter 4: Programming using Sprite Kit - This chapter describes howthe tools in Sprite Kit can be used to help in the development process, and howI implemented some of them in our game. Some alternative methods for addingsprites and actions without Sprite Kit are also presented.

Chapter 5: Result - This chapter describes the result after the implemen-tation is finished. Some suggestions for future work are also presented.

Chapter 6: Discussion - In this chapter I will discuss how I felt it was towork with Sprite Kit and reflect on my own personal experiences with the gameengine. I will also take up some pros and cons.

Chapter 7: Conclusion - In this last chapter I will answer my questionsbased on the experience I have gained during the project. Is Sprite Kit a goodgame engine for game development?

3

Page 9: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Chapter 2

Theoretical Background

2.1 Why to use a game engine?

Jonathan Blow [3] mention that in recent years games have become more com-plex and now the primary technical challenge is simply getting the code to workto produce an end result. There is such a wide variety of algorithms to knowabout and so much work overall that is just needs to be done to make a game.

When making a game there are different levels of programming. Gameplaycode control the overall content rules, and high-level behavior of the game. Sit-ting below gameplay code is the engine, which provides all the basic mechanismsfor simulation and I/O. Engine code is more difficult to write than gameplaycode because it requires advanced knowledge and must be held to more strin-gent quality and performance standards.

To reduce the workload when making a game, game engines exist to take careof the engine code. According to a study made by Kasurinen et al. [10] mostof the interviewed game developing organizations use complex third party com-ponents such as game engines, allowing the development team to focus on thegameplay code and game core functionalities. Jingming Xie [7] adds that themobile market is growing quickly and it is full of competition. This makes thespeed and quality of developing a mobile game to important factors consideredby game companies. Game engines can improve the efficiency of making gamesby comprehensive development support.

4

Page 10: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

2.2 iOS game development: a history

In early days, the only option to make a game for iOS was with OpenGL ES,which is a lightweight subset of desktop OpenGL. The API is optimized for themobile platforms and is the lowest-level cross platform API used to program 2Dand 3D graphics on the iPhone [10]. For many people just starting with gamedevelopment OpenGL ES could be a big barrier to entry. To solve this problemthird-party developers released game frameworks such as Cocos2D, Sparrow,Corona, or Unity that is some popular frameworks built on top of OpenGL.Many of the games at the top of the App Store charts were made with theseframeworks, and for many developers some of these frameworks was their entrypoint into the world of game development.

Since none of these frameworks was written or supported by Apple there couldbe problem when new versions of iOS where released, or with integrating otherApple API’s into the system. To resolve this, with iOS7 Apple released a brandnew framework for making 2D games: Sprite Kit. Its API is very similar to Co-cos2D, with similar types for the sprites, actions and scenes as used in Cocos2D.So people that already have experience with Cocos2D should have no problemto learn Sprite Kit.

2.3 Introduction to Sprite Kit

Sprite Kit is fully supported by Apple and heavily optimized to make 2D gamesfor both iOS and OSX. Sprite Kit empowers the developer to build fully featuredgames using Objective-C. The framework provides a graphics rendering andanimation infrastructure that can be used to animate arbitrary textured images,or sprites. It uses the graphics hardware available on the hosting device tocomposite 2D images at high frame rates [2]. Sprite Kit also provides otherfunctionality that is useful for games such as basic sound playback support, anaction system, the possibility to render text and a built in physics engine. Inaddition, Xcode provides built-in support for Sprite Kit and a particle emittereditor is built into Xcode as an inspector in the right pane that make it possibleto create complex particle effects to your game directly in Xcode.

5

Page 11: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

2.3.1 The game loop

Behind the scenes Sprite Kit runs an endless loop, often referred to as the gameloop, which looks like this:

Figure 2.1: The Sprite Kit game loop [2]

Each individual picture that you draw is called a frame. Games typically tryto draw frames between 30 to 60 times per second so that the animations feelsmooth. For each frame Sprite Kit does the following as shown in figure 2.1:

1. Calls a method on your scene called -update: which runs to every frame.This is the place to put code that you want to run every frame. It is agood spot for checking victory or lose conditions and update the positionor rotation of your sprites.

2. Sprite kit comes with many built in actions which allows the programmerto rotate, scale or change a sprite’s position over time with just one lineof code. These actions are evaluated after the update method. Code forcollision detection is therefore best to place in the -didEveluateActionsmethod after Sprite Kit has evaluated the actions and all the sprites arein their new positions.

3. After executing update: and evaluating the actions, and just before ren-dering the sprites onscreen, Sprite Kit performs the physics simulationsand move the sprites accordingly. After this occurs, there is a chance toperform any code you might like in the -didSimulatePhysics method.This can be code that you want to use to check for conditions or positionsof your sprites every frame after the physics engine has done its job.

4. Finally Sprite Kit draws all of the objects that are in your scene graph.This is done behind the scene where Sprite Kit is issuing OpenGL draws

6

Page 12: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

for the programmer. Sprite Kit tries to draw frames as fast as possible,up to 60 FPS (frames per second). But if the update method is to slowdue to heavy algorithms or if Sprite Kit has to draw more sprites at oncethan the hardware can handle, the frame rate might decrease.

2.4 Sprite Kit basics

When using Sprite Kit nodes are the main building blocks for all content. Ev-erything that appears on the screen in Sprite Kit derives from a class calledSKNode. The SKNode has no size or contents itself but the position, rota-tion, scale, alpha and other attributes as seen in figure 2.2 can be set.

Figure 2.2: SKScene and SKSpriteNode inherits from SKNode [2].

SKNode can also be used to organize other nodes such as using multiple layersto separate the background and gameplay nodes. Also by setting propertiessuch as scale, position and visibility on a SKNode will influence all of its childnodes. Hiding or changing the position of a parent node will hide or change thepositions of all its children.

Animation and rendering is performed by an SKView object that is responsiblefor displaying content on the screen. Contents in your game are organized intoscenes. A scene holds sprites and all the other content to be rendered which arerepresented by SKScene objects.

7

Page 13: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

2.4.1 SKScene

SKScene inherits from SKEffectsNode which inherits from SKNode. Onlyone scene can be presented at a time, and when your scene is presented by theSKView, the Sprite Kit game loop begins and processes each frame in the ordershown in section 2.3.1.

2.4.2 Sprite Kit nodes

As mention in section 2.4 everything that appears on the screen in Sprite Kitderives from a class called SKNode. The following nodes are all availablein Sprite Kit and derives from SKNode. The first three nodes are the mostcommon and used in almost all games created with Sprite Kit. The four laternodes are more advanced types of nodes used for adding cool and unique effectsinto your game:

1. SKSpriteNode: This node is the most common SKNode subclass thatare used when building a game with Sprite Kit. The node draws texturesfrom images ”sprites” or a colored square or a textured image blendedwith a color.

2. SKLabelNode: This node is another common node used for displayingtext as a sprite in a single line. It support all the system fonts, customfonts and will also respond to any SKAction just like other nodes thatderive from SKNode.

3. SKEmitterNode: This node creates and render particle systems. Theparticles are owned by Sprite Kit and cannot be accessed directly. Emit-ters can either be coded or created using the Particle Emitter Editor.

4. SKCropNode: This node allows the programmer to apply a mask toa node or node tree, effectively ”cropping” its children to only display acertain area.

5. SKVideoNode: This node allows the programmer to play video contentright within your games by simply pass in the URL of the video to playor initialize it with an AVPlayer.

6. SKShapeNode: This node draws an arbitrary shape from a CGPathpath. It is possible to apply different colors and glow to the stroke and fillthe path.

7. SKEffectNode: This node allows the programmer to apply special effectsto its children nodes. It applies a filter effect to an image and can modifya sprite’s vibrance, hue, blur or exposure.

8

Page 14: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

2.4.3 SKActions

SKActions are used to perform the sprites animations and to play sound ef-fects. SKActions can be applied to any of the nodes mention above in section2.4.2 in order to rotate, scale or change the nodes position. The SKActionsare designed to make it easier to do things that would normally require theprogrammer to write a lot of code if he were to roll these actions by himself.The SKActions can also be grouped (run in parallel), sequenced (run serially),repeated and some can even be reversed. Some of the most common groups ofactions are described below:

1. Move actions: These actions are used to change a sprites x and y posi-tions to move a sprite to a particular point in space. These actions alsoallow the programmer to specify a change in only the x or y position wherethe other axis is assumed to remain the same.

2. Sequence action: The real power of actions lies in how easily they canbe chained together. The sequence action is one of the most useful andcommonly used actions when programming with Sprite Kit. The sequenceaction will run one action after another, which allows for more complexbehavior.

3. Group action: Sometimes the programmer do not want to run actionsin sequence and instead run two actions at the exact same time. For thissort of multitasking the group action can be used. It works similar tothe sequence actions where you pass in a list of actions. But instead ofrunning them one at time, a group action runs them all at once.

4. Reversed action: This actions gives the possibility to reverse certainactions in Sprite Kit. It results is a new action that is the opposite of theoriginal action. For example, if you run a move action on a sprite, it ispossible to run the reverse of that action and the sprite will go back towhere it came from to its original position. Notice that not all actions arereversible in Sprite Kit.

5. Repeat actions: These actions are used to repeat an action a certainnumber of times or an endless number of times by repeating an actionforever.

6. Animation action: This action is used for adding animations to yoursprites which is an easy way to add a lot of polish and fun to your game.To run an animation action, you first need to gather a list of texturesthat will make up the frames for the animation. A sprite has a textureassigned to it, but you can always swap out the texture with another.That is exactly what the animation action does, it swap out your sprite’stexture over time, with a short delay between each frame.

7. Sound action: This action are the one that plays sound effects. Notethat the node on which you run this action does not matter. Normallythe action runs as an action on the scene itself.

9

Page 15: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

2.4.4 Particle emitter editor

Particle system are designed to create special effects in your game and can beused for a wide range of special effects like the smoke effect shown in figure 2.3

Figure 2.3: Smoke made with the Sprite Kit.

Table 2.1: Shows just a few effects you might simulate with particle systems:

smoke water fogstar fields snow rainfire explosions magical potionssparks blood bubbles

As seen in tabel 2.1 it is impossible to imagine all you could do with particlesystem, it pays to be creative.

With particle systems, the special effects are generated by one small textureand a configuration file, greatly reducing the memory requirements and allow-ing real-time editing. A particle is two triangles drawn together to create aquad. This quad is then textured, colored and rendered to the screen. Duringeach frame, the particle system looks at each individual particle it owns andadvances it according to the systems configuration.

To achieve a special effect like this without particle systems, you will have tomake a traditional frame-by-frame animation, which would require many imagestaking up much texture space and memory requirements.

10

Page 16: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

A particle emitter editor is built into Xcode as an inspector in the right pane.It renders the emitter live in an SKView so that the programmer can makechanges to the emitter and see the result live as he tweak its properties.

2.4.5 Physics engine

As mention earlier sprites can be moved around by running actions on them.But what if the programmer wants to simulate real-life behavior, like bouncing,collisions and other physical phenomenas? It is possible to accomplish this witha lot of mathematical equations that will require a lot of code, but there is aneasier way. Sprite Kit has a built in physics engine that can be used to makeobjects move in a realistic way.

Under the hood, Sprite Kit uses an open source library called Box2D to performall the physics calculations. The library is used by many other popular gameengines and games for iPhone, Android, BlackBerry, Nintendo DS, Wii, OSXand Windows. However Apple does not expose Box2D directly - instead, itabstracts it behind its own Objective-C API calls in Sprite Kit. The reason forthis seems to be because Box2D are written in C++ rather than Objective-C,and that the library could stand to be more user-friendly for beginning devel-opers. As seen in figure 2.4 Box2D is walled so well that Apple could changethe physics engine in a later version of iOS and the most programmer wouldprobably not notice a thing.

Figure 2.4: In Sprite Kit you get access to Box2D through a friendly, polishedApple-style API [15].

2.4.6 Texture atlases

A texture atlas is a single image file made up of many smaller image files. Im-age location within the atlas is mapped in an atlas plist. Packing images intoa texture atlas will bring many benefits. The main advantage of using tex-ture atlases is that it decreases your game’s memory usage. Since memory isan expensive resource on iOS devices it is very important to keep the memory

11

Page 17: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

as low as possible for your game apps. The iPhone 4S has for example only512MB memory versus 4GB+ on laptop computers. The more you can reducethe memory requirements, the faster your app will run and it will prevent yourapp from crashing due to insufficient memory. When memory gets low, iOS ter-minates apps that are running in the background, beginning with the largest.By decreasing your memory requirements, you decrease the chances of iOS ter-minating your app when it is in the background.

Above and beyond the performance boost you get from using less memory yourapp will also use fewer OpenGL calls. To draw a texture on the screen withOpenGL, there are two steps:

1. Bind the texture: First OpenGL needs to make the texture you want touse active. This is called binding the texture.

2. Draw the texture: Then OpenGL draws the texture this is two expensiveoperations.

If you are just using sprites directly, every time you draw a sprite you have toperform both of these steps. Since both of these calls are expensive, once youhave a lot of sprites in your game your games frame rate will drop as the GPUspends more and more time binding and drawing the individual textures. Sincetexture atlases combine all of your sprites into a single larger image, you onlyneed about one bind call and one draw call total for all the sprites that are partof the texture atlas. With fewer OpenGL calls, your game runs faster.

Sprite Kit comes with texture atlas support built into Xcode 5.

2.5 Game engine requirements

There are several game engines out there today. To know which one to choosecan be a hard choice and depends on the needs and requirements for the game.The game covered by this thesis is a turn based strategy game designed for iOSdevices. More detailed information about the game will be found in chapter 3.The following technical requirements has been taken into account and must befulfilled by our game engine:

• Build fully featured, high quality games for iOS.

• Free to use (or with a very low onetime cost).

• Well written official documentation.

• Easy to use and a lots of well made tutorials.

12

Page 18: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

2.5.1 Why we chose Sprite Kit

Sprite Kit fulfills all the criterias mention in section 2.5. The framework useObjective-C to create games for iOS and render 2D frames at high frame ratesusing the device’s (iPhone,iPad, Macbook Pro etc.) graphics processor. SpriteKit is also free to use and the only thing the programmer needs to publish agame on App Store, and to test it on an actual device, is an Apple developerlicense for $99 dollars.

In conjunction with the release of Sprite Kit, Apple also launched Sprite Kitprogramming guide which is Apples official documentation containing a lot ofinformation and coding examples about how program with Sprite Kit. RayWendrich [16] has also published many tutorials for Sprite Kit on his websitewhich is a good place for beginners (but even more advance users) to start look-ing for programming examples. Some of those tutorials are summarized andforms a part of the book iOS games by tutorials [15], which is a good book forprogrammer starting with iOS game development and want to increase theirknowledge in how to work with Sprite Kit.

According to Nils Kbler [11] simplicity is also something that characterizesSprite Kit and it seems to bee very straight forward and easy to jump rightinto. The API is intuitive and easy to use where game objects are organized ina tree structure and every object inherits from SKNode.

There are also other game engines that fulfills the criterias mention in sec-tion 2.5. The game engine most similar to Sprite Kit is Cocos2D that also usesobjective C to create games for iOS. Unity 2D is another good game enginethat provides the developer with many good tools for creating 2d games fordifferent platforms. The reason why Sprite Kit was chosen was because it wasnew and just released at the time when the development of the game for thisthesis started. Since we wanted to try something new and focused mainly ondevelopment for iOS 7 and higher we decided to try Sprite Kit.

13

Page 19: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Chapter 3

Introduction to the game

3.1 A turn based strategy game

The game is a turn based strategy game where players take turns when playing.This is distinguished from real time strategy where all players play simultane-ously. Chess is widely considered the ultimate turn-based strategy game as it isone of the oldest and most competitive games of its kind [8]. Turn-based tacticalgameplay is characterized by military tactics, in general small-scale confronta-tions. The player has to make smart moves and think carefully before movinghis units. It is also important to keep in mind what will happens next afteryour move, to always make it more difficult for your enemy to strike back.

The Heroes of Might and Magic series [14] has been one of the biggest sourcesof inspiration for the game. Especially the old and popular games Heroes ofMight and Magic II and III.

3.2 The structure of the game

The goal was to implement a turn based strategy game adapted for iPhonesand ipads. One thing that had to be taken into consideration is that the screensizes of those devices are smaller compared to laptop computers and instead ofmouse they use touch for navigation and interaction. The game must thereforebe designed to fit those criterias which made us to make the game as simpleand clean as possible to fit the requirements for the selected platforms.

To create a simple architecture for the game a decision was made that thegame should consist of three main scenes:

14

Page 20: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

• The map scene: When the player first enters the game this is the firstscene displayed. The scene is shown in figure 3.1 and all the other scenescan be accessed from this one.

Figure 3.1: The map scene

The scene can be seen as a map of the world where the player constantlyreturns after battles to advance in the game and to move on to higherlevels. The scene helps the player to get an overview of the game and tonavigate to other more important scenes.

15

Page 21: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

• The battle view: After the player has selected a level from the mapscene the player will enter this scene. This is the scene that contains thecore gameplay and where the player spends most of the time while playingour game. The scene is shown in figure 3.2 and it is here where the battlesare determined.

Figure 3.2: The battle scene

The turn-based tactical gameplay described in section 3.1 take place inthis scene and the players move their units in turns in order to knock outthe units of the opponent’s army. The scene will look slightly differentdepending on level and the enemy troops encountered.

16

Page 22: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

• The castle scene: This scene is accessible from the map scene when theplayer hits the castle on the map. The scene is shown in figure 3.3 and thisis the place where the player can buy and upgrade new units and itemsto be used for the battles.

Figure 3.3: The castle scene

For the moment the scene contains two different shops. One trainingcamp for unlocking, buying and upgrade the units that later are used inthe battle scene. And another shop for buying items that can be usedtogether with the units to give them advantages in battles.

17

Page 23: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Chapter 4

Programming using SpriteKit

As mention in section 1.2 the purpose of this thesis is to investigate how SpriteKit can be used to simplify the development process for programmers. JingmingXie [7] mention that the main technologies in game engines commonly includescene management, rendering, physics systems, etc. The following sections willdiscuss them and some other technologies that I find important when making a2D game for mobile devices.

4.1 Scene management

A scene manager manages the game objects, organizes their relationships andis simply handling replacing one scene with another. Various types of gamesmakes it hard to design a data structure suitable for all games. A tree structureis the most commonly used method [7] also used by Sprite Kit [2]. The point ofhaving a scene manager is to provide a reusable starting point for the game.

Scenes are the visual layers of the game that act as a parent container forall other visible nodes in the scene. In every game there are multiple scenes. Inour game there are at least tree scenes described in section 3.2. Multiple sceneshelps the game developer to get a better organization and overview of the game.It also helps to break apart the code into manageable chunks where each scenecontains discrete bits of game logic. As mention in section 2.4.1 SkScene isthe main object used to draw other objects in Sprite Kit. SkScene is the rootnode in a tree of Sprite Kit nodes. [2]

When creating a new project using the ”Sprite Kit Game Template” (figure4.1) a storyboard with a view controller, and a view set to SKView is createdfor you. The project game template will also create header and class files calledMyScene.h and MyScene.m that derives from SKScene.

18

Page 24: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Figure 4.1: The battle scene

These are the main files for the programmer to work with when building a game.The files can be renamed and other set of scene files can also be added to yourgame. To create a new set of scene files to your game, you simply create a newclass that derives from SKScene. Xcode will generate two new files for you,where you can implement the methods you want to get the desired functionality.

In Sprite Kit only one scene can be visible and running at a time [5]. Tonavigate trough your game’s UI the current scene has to be replaced with a newone. The new scene is visible and old scene is dead. Transition from one sceneto another is easily done in Sprite Kit with the following steps: [15]

Listing 4.1: Transition between scenes

1 //12 SKScene ∗gameScene =3 [[ GameScene alloc] initWithSize:CGSizeMake(1024, 768)];45 //26 SKTransition ∗reveal =7 [SKTransition flipHorizontalWithDuration:0.5];89 //3

10 [ self .scene.view presentScene:gameScene transition:reveal ];

1. First you create an instance of the scene itself. -initWithSize: is thecustom initializer setting the size for the window.

19

Page 25: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

2. Next you create a transition object that specifies the type of animation todisplay when the new scene is presented. There are cross fade transitions,flip transitions, door-opening transitions, and many more.

3. Finally you call the SKView’s presentScene:transtion: method whereyou pass in your scene and the transition created in the two earlier steps.

4.2 Rendering

Rendering generate an image of the objects. That includes primitives rendering,occlusion culling, texture mapping, model rendering, lighting, shading, LODmanagement, and HUD rendering, etc. Each of the above subjects can be di-vided as smaller sub-parts for proposing specific algorithms. For example, thereare planar shadow, shadow volume and shadow map algorithms for shading.Gouraud, Phong and ray tracing algorithms are used to deal with lighting [7].

To simulate the world in games takes a large number of calculations. OpenGLES is the subset of OpenGL, which is designed for mobile devices. OpenGLES is the lowest-level API that is used to program 2D and 3D graphics on theiPhone [17]. Sprite Kit is built on top of OpenGL ES and contains everythingdevelopers need to write a 2D game from scratch, without having to worry aboutOpenGL. OpenGL is notoriously difficult to learn and you have to write a lot ofcode to get a simple game working. Because of this, many developers prefer touse an engine that allows them to deal with complex graphics in a discrete way,rather than having to worry about every triangle and lighting algorithm. Underthe hood, all game engines designed for mobile devices use OpenGL ES, theyjust hide the lower level details from the programmer to make things simpler [15].

When making a 2D game, you usually put images on the screen representingyour game’s hero, enemies, obstacles and so on. Each of these images is called asprite. Figure 4.2 shows a scene from the game with all the containing sprites.

20

Page 26: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Figure 4.2: Many images are put on top of each other to create the map scene.The main sprites in the scene are identified.

The two following sections will present two different methods to programmati-cally add a sprite to your game. The first method, without the use of a gameengine, which is more complex and require more code and experience. The sec-ond method demonstrates the benefits of using Sprite Kit which makes it easierand faster for programmers to add sprites to their games.

4.2.1 Adding a sprite using OpenGL ES and GLKit

GLKit is a set of APIs that makes working with OpenGL ES on iOS mucheasier than it used to be. GLKit saves you from writing code regarding settingup a basic display, creating basic shaders, preforming vector/matrix math andloading textures. The following code examples in this section is taken from aOpenGL ES 2.0 and GLKit tutorial made by Wenderlich [15]

To add a sprite to your scene using OpenGL ES 2.0 and GLKit we must imple-ment a sprite class. Two new files named SGGSprite.h and SGGSprite.mis created. The SGGSprite.h contain the interface for our sprite class. Thesetup in listing 4.2 is the simplest possible.

21

Page 27: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Listing 4.2: SGGSprite.h

1 #import <Foundation/Foundation.h>2 #import <GLKit/GLKit.h>34 @interface SGGSprite : NSObject56 − (id)initWithFile :(NSString ∗)fileName effect :(GLKBaseEffect ∗)effect;7 − (void)render;89 @end

We allow the user to specify the image file for the sprite to display, and theGLKBaseEffect (shader) that will render it. We also define a routine that theGLKViewCintroller will call to render the sprite.

The SGGSprite.m contains most of the code for our sprite class. We startat the top of the file shown in listing 4.3

Listing 4.3: SGGSprite.m

1 #import ”SGGSprite.h”23 typedef struct {4 CGPoint geometryVertex;5 CGPoint textureVertex;6 } TexturedVertex;78 typedef struct {9 TexturedVertex bl;

10 TexturedVertex br;11 TexturedVertex tl;12 TexturedVertex tr;13 } TexturedQuad;

At the top line the header file is imported, and next some structures neededto store information about the sprite is created. The TexturedVertex is astructure that will keep track of the information we need at each corner of thesprite. The second structure, TexturedQuad, contains 4 TexturedVertexstructures, one for each corner.

After defining the data structure that hold the geometry and texture vertexvalues we have to set it up. This is shown in listing 4.4

22

Page 28: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Listing 4.4: SGGSprite.m

1 @interface SGGSprite()23 @property (strong) GLKBaseEffect ∗ effect;4 @property (assign) TexturedQuad quad;5 @property (strong) GLKTextureInfo ∗ textureInfo;67 @end89 @implementation SGGSprite

10 @synthesize effect = effect ;11 @synthesize quad = quad;12 @synthesize textureInfo = textureInfo;

Here we define an synthesize three private properties:

1. GLKBaseEffect * effect: The effect (shader) that we will use to renderthe sprite.

2. TexturedQuad quad: The instance of our TexturedQuad structure.

3. GLKTextureInfo * textureInfo: We are going to use GLKits GLK-TextureLoader class to easily load our texture. It will return some infoabout the texture that is stored here.

We continue on by adding this next:

Listing 4.5: SGGSprite.m

1 − (id)initWithFile :(NSString ∗)fileName effect :(GLKBaseEffect ∗)effect {2 if (( self = [super init ]) ) {3 // 14 self . effect = effect ;56 // 27 NSDictionary ∗ options = [NSDictionary

dictionaryWithObjectsAndKeys:8 [NSNumber numberWithBool:YES],9 GLKTextureLoaderOriginBottomLeft,

10 nil ];1112 // 313 NSError ∗ error;14 NSString ∗path = [[NSBundle mainBundle] pathForResource:fileName

ofType:nil];15 // 416 self . textureInfo = [GLKTextureLoader textureWithContentsOfFile:

path options:options error:&error];17 if ( self . textureInfo == nil) {

23

Page 29: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

18 NSLog(@”Error loading file: %@”, [error localizedDescription ]) ;19 return nil ;20 }21 // TODO: Set up Textured Quad22 }23 return self ;24 }

Here we create the initializer for our class:

1. Stores the GLKBaseEffect that will be used to render the sprite.

2. Sets up the options so that when we load the texture, the origin of thetexture will be considered the bottom left.

3. Gets the path to the file we are going to load. The filename is passed in.Note that if you pass nil as the type, it will allow you to enter the fullfilename in the first parameter.

4. Finally loads the texture with the GLKTextureLoader class.

Next this is added after the TODO in listing 4.5:

Listing 4.6: SGGSprite.m

1 TexturedQuad newQuad;2 newQuad.bl.geometryVertex = CGPointMake(0, 0);3 newQuad.br.geometryVertex = CGPointMake(self.textureInfo.width, 0);4 newQuad.tl.geometryVertex = CGPointMake(0, self.textureInfo.height);5 newQuad.tr.geometryVertex = CGPointMake(self.textureInfo.width, self.

textureInfo.height);67 newQuad.bl.textureVertex = CGPointMake(0, 0);8 newQuad.br.textureVertex = CGPointMake(1, 0);9 newQuad.tl.textureVertex = CGPointMake(0, 1);

10 newQuad.tr.textureVertex = CGPointMake(1, 1);11 self .quad = newQuad;

Were going to fill in the TexturedQuad (and its four TexturedVertex) struc-ture with values based on the size of the sprite we are displaying:

24

Page 30: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Figure 4.3: This fills in our quad as described in listing 4.6.

Note that the texture vertex values will be the same no matter what sprite youuse, since we always want to map the texture the same way with respect to thevarious corners. The geometry vertex values will change though, based on thesize of the texture.

The final bit to add for our sprite class:

Listing 4.7: SGGSprite.m

1 − (void)render {23 // 14 self . effect .texture2d0.name = self.textureInfo.name;5 self . effect .texture2d0.enabled = YES;67 // 28 [ self . effect prepareToDraw];9

10 // 311 glEnableVertexAttribArray(GLKVertexAttribPosition);12 glEnableVertexAttribArray(GLKVertexAttribTexCoord0);1314 // 415 long offset = (long)& quad;16 glVertexAttribPointer(GLKVertexAttribPosition, 2, GL FLOAT,

GL FALSE, sizeof(TexturedVertex), (void ∗) (offset + offsetof(TexturedVertex, geometryVertex)));

17 glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL FLOAT,GL FALSE, sizeof(TexturedVertex), (void ∗) (offset + offsetof(TexturedVertex, textureVertex)));

18

25

Page 31: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

19 // 520 glDrawArrays(GL TRIANGLE STRIP, 0, 4);2122 }2324 @end

1. When you use a GLKBaseEffect to render geometry, you can spec-ify a texture to use for the drawing. You do this by setting the tex-ture2d0.name to the textureInfo.name, and setting texture2d0.enabledto YES.

2. Before you draw anything, you have to call prepareToDraw on the GLK-BaseEffect.

3. There are two pieces of information we want to pass to the effect/shader:the position and texture coordinate of each vertex. We use this functionto enable us to pass the values through.

4. Next we need to actually send each piece of data. We do that via theglVertexAttribPointer method. For example, the first function says Iwant to send some position values. Im going to send 2 floats over. Afteryou read the first two floats, advance the size of the TexturedVertexstructure to find the next two. And heres a pointer to where you can findthe first vertex.

5. Finally, we draw the geometry, specifying 4 vertices of data drawn as atriangle strip.

This sprite class is now complete and ready to use in order to draw a simplesprite to the screen.

4.2.2 Adding a sprite using Sprite Kit

Sprite Kit has a special class that makes it easier to create and work withsprites, called SKSpriteNode. So instead of writing your own sprite class likethe example in the previous section, the programmer can use SKSpriteNodeto add all the sprites to the game.

To add a sprite to a Sprite Kit scene is very simple. You just use the spriteN-odeWithImageNamed: method, and pass in the name of the image as seenin listing 4.8. Finally you call addChild: to add it as a child of the scene, orone of the scenes descendent nodes [2].

Listing 4.8: Adding a sprite in Sprite Kit

1 SKSpriteNode ∗bg =2 [SKSpriteNode spriteNodeWithImageNamed:@”background”];3 [ self addChild:bg];

26

Page 32: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Note that you don’t need to pass the image’s extension. Sprit Kit will by defaultlook for png images, so the extension is not necessary. If your images are inother formats, such as jpg, you will need to add the extension [15]. So what tookus a tremendous amount of code to achieve with OpenGL ES 2.0 and GLKitcan be done with Sprite Kit with only 2-3 lines of code. All the sprites in ourgame is added with SKSpriteNodes.

4.3 HUD rendering

In games, the term HUD takes it name from the head-up displays used in modernaircraft. The HUD is the method by which information is visually conveyed tothe player as a part of a game’s user interface. The HUD is frequently usedto simultaneously display several pieces of information including, how muchhealth the player has, items available, and an indication of game progressionsuch as score or level. This makes the HUD an invaluable method of conveyinginformation to the player during a game [18]. By looking at the map and castlescene in our game the HUD can be found in the left lower corner where an iconof the Hero is displayed as seen in figure 4.4.

Figure 4.4: The lower left corner of the map scene.

To the right of the hero icon a status bar is found displaying the gold collectedand the level reached by the hero. The purple indicates your heros experienceand the experience needed to reach the next level. Here the HUD layer is createdwith a green status bar and an icon of the hero which both are SKSpriteN-odes. The text on the other hand is created with an SKLabelNode which isperfect for displaying text as a sprite in a single line.

27

Page 33: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

It is often useful in games to display text to help keep your player informed.SKLabelNode supports all the system fonts, custom fonts and derives fromSKNode. Creating a label is easy as seen in listing 4.9 [15]

Listing 4.9: Adding a label in Sprite Kit

1 SKLabelNode ∗ label =2 [SKLabelNode labelNodeWithFontNamed:fontName];3 label . text = @”your text here!”;4 label . fontSize = 20.0;5 label . position = yourPosition;6 [ self addChild:label ];

You simply call labelNodeWithFontName:, and pass in the name of the font.Then you set the text to what you want the font to display and the font size.Finally just lite other nodes, you can position it and add it as a child of anothernode or to the scene itself as in this case.

In the battle scene seen in figure 4.5 the Hud can be found in all the four cor-ners indicating buttons, to show the units health, the items available and whichspecial abilities to use. All the buttons are created by receiving touch callbacksfrom SKSpriteNodes and also the health bar above the units is built up withSKSpriteNodes where each health indicator is an separate SKSpriteNode.

Figure 4.5: A popup shown in the battle scene

Popups are also used in the game to show information for the player as seen infigure 4.5. This popup shows specific information about the unit telling which

28

Page 34: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

rank it belongs to. The basic attack damage, health, movement speed and theunits special abilities can also be found under the icon. At the bottom of thepopup an little description of the unit can be read .

Unfortunately SKLabelNode does not support multiline functionality whichmeans that it is not possible to write more than one line of text. To writea longer text with line breaks, as the description of the unit at the bottomof the popup, without having to create many SKLabelNodes an DSMulti-lineLabelNode can be used. DSMultilineLabelNode does not originallycome with Sprite Kit but can be imported to your project by downloading anextended class created by Allwein [19]. DSMultilineLabelNode support allthe properties and methods of SKLabelNode. The main difference to usingan SKLabelNode is that you may specify the property paragrapWith as seenin listing 4.10

Listing 4.10: Adding a DSMultilineLabelNode

1 DSMultilineLabelNode ∗ textField =2 [DSMultilineLabelNode labelNodeWithFontNamed:fontName];3 textField .text = @”your text here!”;4 textField . fontSize = 20.0;5 textField .paragraphWidth = 200;6 textField . position = yourPosition;7 [ self addChild:textField];

paragrapWith is the value in pixels as to how wide you want your label nodeto expand before creating new lines.

Drawing text seems quite easy when using SpriteKit but it is often a hardtask without the use of an game engine for most beginning game developers. InopenGL ES there is no API that renders text out of the box. This means youhave to create one yourself. There are several methods one can use to rendertext on screen. Each has his advantages and its disadvantages. One commonapproach involves creating a font atlas texture, and then creating a quad foreach letter with just the right placement and texture coordinates. Hollander[20] has written a article where he shows a basic implementation of this methodwith OpenGL ES 2.0. As can be seen by following the article there are morework and code needed to render text with that method, compared by using anSKLabelNode with Sprite Kit.

29

Page 35: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

4.4 Actions

Drawing sprites is useful, but a static image is a picture and not a game. Toadd gameplay, you need to be able to move your sprites around the screen andperform other logic. An action is an object that defines a change you want tomake to the scene. If you want to move a sprite across the screen, you createa move action and tell the sprite node to run that action. Sprite Kit will thenanimate that sprite’s position until the action completes.

As mention in section 2.4.3 Sprite Kit has a class called SKAction that can beused to move and change the positions of the sprites. In our game SKActionis used to move the hero between the different levels in the map scene. Alsoin the battle scene all the turn based movement on the hexagonal grid is donewith SKActions. Animation effects occurring on the popups in our game isyet another way to use SkActions.

SKAction make it incredibly easy to do things that would normally requirethe programmer to write a lot of code. To create an action in Sprite Kit, youcall one of several static constructors on the SKAction class. In listing 4.11 theconstructor moveTO:duration: is called. This particular constructor returnsan action that moves a sprite to a specified position, over a specified duration(in seconds) [15].

Listing 4.11: A move action

1 SKAction ∗actionMove =2 [SKAction moveTo:CGPointMake(self.size.width/2, self.size.height/2)3 duration :2.0];4 [ sprite runAction:actionMove];

Here you set up the action to move the sprite to the center off the screen atwhatever speed is necessary to take it from its current position to the center intwo seconds. Once an action has been created, you need to run it. You can runan action on any SKNode by calling runAction:, as you did in the above code.

This can also be done manually in Sprite Kit without the use of SKAction.You might then update the sprites position each frame according to a velocity.This requires more work and to show how this is done in Sprite Kit we add thefollowing new method [15]:

30

Page 36: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Listing 4.12: Moving a sprite manually

1 − (void)moveSprite:(SKSpriteNode ∗)sprite toward:(CGPoint)locationvelocity:(CGPoint)velocity

2 {3 // 14 CGPoint offset = CGPointMake(location.x − sprite.position.x,5 location .y − sprite . position .y);6 // 27 CGFloat length =8 sqrtf ( offset .x ∗ offset .x + offset .y ∗ offset .y);9

10 // 311 CGPoint direction = CGPointMake(offset.x / length,12 offset .y / length);13 velocity =14 CGPointMake(direction.x ∗ velocity.x,15 direction .y ∗ velocity .y);16 }

1. First the offset between the new location you want to reach, and thelocation of the sprites current position, need to be figured out. You getthis by simply subtracting the sprites position from the new position. Bysubtracting these two positions, you get something with a direction andlength, the offset vector.

2. The next step is to figure out the length of the offset vector. You can thinkof the offset vector as the hypotenuse of a triangle, where the lengths ofthe other two sides of the triangle are defined by the x and y componentsof the vector. To find the length of the hypotenuse Pythagorean theoremcan be used. Put this theory into practice and the following line can beadded.

3. The offset vector is converted to a unit vector, which is a vector of length1. Dividing the offset vectors x and y components by the offset vectorslength does this. The vector is now normalized, and once we have the unitvector it is easy to multiply it by a velocity to make it to the desirablelength.

Finally to use this method it has to be placed inside the update: methodaccording to the Sprite Kit game loop in section 2.3.1. Then the sprites positionwill be processed each frame. The method can be called with one line as seenin listing 4.13

Listing 4.13: Calling the moveSprite method

1 [ self moveSprite: sprite towards:CGPointMake(size.width/2, size.height/2)velocity:CGPointMake(120, 0)];

31

Page 37: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

The purpose of SkActions is to assist the programmers, and provide them witha set of actions that is frequently used in game development. If you have anaction that is used repeatedly in your game, a single instance of the action canbe created and reused whenever you need a node to execute it.

4.5 Texture Atlases and Animations

A good game cannot only be fun to play it also needs to preform well. Theplayers expect a smooth frame rate while they play without any disturbance.One of the most important optimizations you can make to your game is to usetexture atlases. In our game almost every sprite belongs to a texture atlas. Wehave three larger texture atlases for all the objects in our three game scenesdescribed in section 3.2. As well as one extra texture atlas that contains allthe elements for the popup windows. Since all the units is our game consist ofseparate body parts used for animations each individual unit also has its owntexture atlas.

As mention in section 2.4.6 Sprite Kit comes with texture atlas support builtinto Xcode 5.

A texture atlas can be created by doing the following [5]:

1. Turn on atlas generation. When using the Sprite Kit Project Template,the Enable Texture Atlas Generation build setting is automaticallyset to YES. In this case, it is not necessary to manually set this yourself.

2. Place all your related image files into a folder on disk called .atlas

3. Drag the folder into your Xcode project

The files in the .atlas will be processed and available for use right away. Whencompiled in the bundle, the folder will have a .atlasc extension. When theproject is built, the following occurs:

1. Textures are automatically combined

2. Automatic image rotation for maximum packing

3. Transparent edges are trimmed

4. Hardware specific atlases are generated

5. According to Apples documentation [2], the maximum texture atlas sizeis 2000x2000 pixels. If more images than can fit 2000x2000 are put into atexture atlas, Xcode will create additional texture atlases until all imagesin the .atlas folder are inside an atlas. A single plist file will be created.

The generated atlas will look something similar like figure 4.6

32

Page 38: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Figure 4.6: A texture atlas of the objects in the map scene

You will see the images packed nice and tight along with a .plist file that hasdescriptive information for each of the packed images including the location ofeach image within the single image file. All this helps to improve developeriteration time. Just utilizing texture atlases can save hundreds of megabytes.Texture atlas references are tracked in memory; when the developer decides toload the same texture, the in-memory texture is used. Loading an image from atexture atlas is almost the same as loading a standalone image as seen in listing4.14 [15].

Listing 4.14: Loading an image from a texture atlas

1 SKTextureAtlas ∗mapAtlas =2 [SKTextureAtlas atlasNamed:@”map”];3 SKTexture ∗ texture = [mapAtlas textureNamed:@”castle”];4 SKSpriteNode ∗ castle =5 [SKSpriteNode spriteNodeWithTexture:texture];

You can use the SKTextureAtlas class to get a reference to a specific textureatlas and the SKTexture class to get a reference to a particular texture withina texture atlas. Then you can create a SKSpriteNode from that texture tohave fine-grained control over which texture atlas a sprite comes from.

Adding animations is a super easy way to add a lot of polish and fun to yourgame. There are various ways to animate your game sprites. The most commonmethod supported by Sprite Kit is to run an animation action as described insection 2.4.3. This method is called frame-by-frame animation and can be donewith the code shown in listing 4.15 [15]:

33

Page 39: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Listing 4.15: Using animation action

1 //12 NSMutableArray ∗animationFrames = [NSMutableArray array];3 SKTextureAtlas ∗bearAtlas = [SKTextureAtlas atlasNamed:@”bear”];45 //26 int numImages = bearAtlas.textureNames.count;7 for ( int i=1; i= numImages; i++)8 {9 NSString ∗textureName = [NSString stringWithFormat:@”bear%d”, i];

10 SKTexture ∗temp = [bearAtlas textureNamed:textureName];11 [animationFrames addObject:temp];12 }13 //314 SKAction ∗bearAnimation =15 [SKAction animateWithTextures:animationFrames timePerFrame:0.1];16 [ bear runAction:[SKAction repeatActionForever:bearAnimation];

1. Fist an array to hold the animation frames and a texture atlas is created

2. The animation textures are then added to the array by looping throughyour images names and try to find a sprite frame by that name in thetexture atlas

3. The array with the animation frames and a time interval is sent to theSKAction animateWithTextures:. Finally this action is set to thebear sprite, repeated over and over again.

For this method to work, a sequence of animated images is needed inside thetexture atlas as seen in figure 4.7.

Figure 4.7: Four separate images that are lined up to show a short animationsequence of a walking bear.

As seen in figure 4.7 a lot of art is needed, especially if you want smooth andgood quality animations.

An alternative method to traditional frame-by-frame animation is to use ananimation tool. Esoteric Software offers an animation tool called Spine [6] thatfocuses specifically on 2D animations for games. Animation in Spine is doneby attaching images to bones and then animating the bones. This means that

34

Page 40: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

the art for your game characters must be divided into body parts in order toanimate as seen in figure 4.8.

Figure 4.8: A texture atlas of our hero’s body parts.

This has numerous benefits over traditional, frame-by-frame animation [6]:

• Smaller size Traditional animation requires an image for each frame ofanimation. Spine animations store only the bone data, which is verysmall, allowing you to pack your game full of unique animations.

• Art requirements Spine animations require much fewer art assets, freeingup time and money better spent on the game.

• Smoothness Spine animations use interpolation so animation is always assmooth as the frame rate.

• Attachments Images attached to bones can be swapped to outfit a char-acter with different items and effects. Animations can be reused for char-acters that look different.

• Mixing Animations can be blended together. For example, a charactercould play a shoot animation while also playing a walk, run or swim ani-mation.

Spine can be used together with Sprite Kit. In our game all the animations forthe units in the battle scene is done with Spine.

After creating your animations, Spine exports animation data in its own, docu-mented JSON and binary formats that are ideal for use with the Spine runtimes.The Spine Runtimes are libraries that allow your game toolkit to load and ren-der animations in your games, just as they do in Spine. Unfortunately Spinedoes not offer an official runtime for Sprite Kit. But there is an third partyruntime that works with Sprite Kit that have been developed by the gamingcommunity and can be found at the website of Spine [6] under runtimes. It does

35

Page 41: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

not fully support all the features of Spine 2D but it does the most importantlike:

• Places Bones and Slot Attachments on SKScene.

• Animates Bone Timelines using SKAction for translate, rotate, and scalesequences

To add a Spine animation to your game with the unofficial runtime you firsthas to import the entire Spine importer folder to your project. You then addthe following lines in Sprite Kit to create a spine object:

Listing 4.16: Creating a spine object

1 #import ”SpineImport.h”23 spine = [SGG Spine node];4 [ spine skeletonFromFileNamed:@”skeletonhero” andAtlasNamed:@”hero”

andUseSkinNamed:Nil];5 spine . position = CGPointMake(self.size.width/2, self. size .height/2);6 spine .zPosition = 0;7 [ spine runAnimation:@”walk” andCount:−1];8 [ self addChild: spine ];

As seen in listing 4.16 you first add the header file of the spine importer whateveryou need to add the runtime. Then you create a spine node and connect it tothe exported JSON file (skeletonhero.json) and the texture atlas (hero.atlas)containing all the art used for the animation. The spine node is then positionedon the screen and the zposition is to specify if the animation should be drawnon top or above other nodes. Finally, you decide which animation to run andhow many times that specific animation should run, before you add the node tothe scene. -1 is typed if you want the animation to be repeated forever.

36

Page 42: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

4.6 Physics systems

Sprite Kit has an built-in 2D physics engine as described in section 2.4.5. Sinceour game is a turn based strategy game the need of a physics engine is notnecessary for our type of game. But for many other game genres like physics-based puzzle games, real time strategy, action and adventure games, physicssimulations might be necessary. For that reason I decided to show how thebuilt-in physics engine in Sprite Kit can be used to help the programmer in theprocess of game development.

Physics simulation are applied by adding an SKPhysicsBody to a node. Youcan think of a physics body as a rough boundary for your sprite that is used forcollision detection as seen in figure 4.9

Figure 4.9: The shape is matched with a close representation.

There are various shapes that can be used to apply physics to a scene. Theseshapes define the node’s ”personal space”. When one node’s shape intersectswith another node’s shape, the method -didBeginContact is called and physicsmay be applied. The shape of the physics body does not need to match theboundaries of the sprite exactly. Usually, you choose a simpler shape so thecollision detection algorithms can run faster. For example, in Figure 4.9, theeagle has a narrow shape that is not well represented by either a circle or arectangle. A convex polygon shape is chosen and fitted to match the spritesartwork. Sprite Kit also provides a few standard shapes, as well as shapesbased on arbitrary paths. Figure 4.10 shows the shapes available [2].

37

Page 43: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Figure 4.10: Physics bodies [2].

Adding a standard shape in Sprite Kit can easily be done with the followingcode shown in listing 4.17 [15]:

Listing 4.17: Attaching a physics body to a circle sprite

1 SKSpriteNode ∗ circle =2 [SKSpriteNode spriteNodeWithImageNamed:@”circle”];3 circle . position = CGPointMake(self.size.width/2,4 self . size .height/2);5 [ self addChild: circle ];67 circle .physicsBody =8 [SKPhysicsBody bodyWithCircleOfRadius: circle.size.width/2];

Here a circle sprite is first created and added to the scene. In this simple exam-ple since the circle sprite uses an image shaped like a circle, you want to createa physics body of roughly the same shape. SKPhysicsBody has a simple fac-tory method called bodyWithCircleOfRadius: that creates a circle-shapedbody.

Once you set a physics body for your sprite, it will move similarly to howit would in real life. When the frame is processed by the scene, the calculationsare performed on the physics bodies attached to the nodes in the scene. Physicsfriction, gravity, and collisions with other physics bodies are some things thatcan be set for the node. Custom forces can also be applied to a body. Physicsbodies are rigid and can not get squished or deformed under pressure, and donot change shape as a consequence of the physics simulation.

All the physics above could also be accomplished without using the built inphysics engine, and instead using a bunch of math to perform the physical cal-

38

Page 44: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

culations. That would require a lot of work and much more code to make theobjects move in a realistic way.

4.7 Special effects

The difference between a good game and a great game is all in the details. Greatgames are filled with a dozed of small details that are so subtle that you mightnot even notice them while you are playing. Polishing a game means payingattention to these details. A common mistake is to stop developing once yourgame reaches a playable state and rush it to the App Store. Pushing your gamefurther by adding more details and cool special effects will improve the visualexperience.

One common way to spice up your game is to add particle systems to cre-ate special effects in your game. As mention in section 2.4.4 Sprite Kit comeswith an particle emitter editor built into Xcode. This editor makes it possible tovisualize and create particle effects to your games. In our game particle emittersare used to create the smoke and fire effect in the map scene and for all the unitsspecial abilities in the fight scene like the bomb explosion seen in figure 4.11.

Figure 4.11: A bomb explosion in the battle scene made with Sprite Kits em-bedded particle system.

To create a particle system with the visual editor, you simply create a new filewith the iOS”\Resource\Sprite Kit Particle File template, which will create a

39

Page 45: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

.sks file that you can edit with the built-in particle system editor. Then in codeyou create an SKEmitterNode with the file like shown in listing 4.18 /cite15:

Listing 4.18: Particle system with the visual editor

1 SKEmitterNode ∗ emitter =2 [NSKeyedUnarchiver unarchiveObjectWithFile:3 [[ NSBundle mainBundle] pathForResource:@”rain” ofType:@”sks”]];4 emitter . position = CGPointMake(100, 100);5 [ self addChild: emitter];

First you load the SKS file from your bundle and unarchive it to obtain anSKEmitterNode. Next you position the particle emitter and add it to thescene.

Not only can you create particle systems with Xcode’s built-in editor visu-ally, you can also create them programmatically. To use a SKEmitterNodeprogrammatically, you simply declare an instance of the node and set up itsproperties, like this [15]:

Listing 4.19: Particle system programmatically

1 SKTexture ∗ rainTexture =2 [SKTexture textureWithImageNamed:@”rainDrop.png”];3 SKEmitterNode ∗ emitterNode = [SKEmitterNode new];4 emitterNode.particleTexture = rainTexture;5 emitterNode.particleBirthRate = 80.0;6 emitterNode.particleColor = [SKColor whiteColor];7 emitterNode.particleSpeed = −450;8 emitterNode.particleSpeedRange = 150;9 emitterNode.particleLifetime = 2.0;

10 emitterNode.particleScale = 0.2;11 emitterNode.particleAlpha = 0.75;12 emitterNode.particleAlphaRange = 0.5;13 emitterNode.particleColorBlendFactor = 1;14 emitterNode.particleScaleRange = 0.5;15 emitterNode.position =16 CGPointMake(CGRectGetWidth(self.frame) / 2, CGRectGetHeight(self.frame

) + 10);17 emitterNode.particlePositionRange =18 CGVectorMake(CGRectGetMaxX(self.frame), 0);19 [ self addChild: emitterNode];

The code above is used for simulating rain. At the first 4 lines a texture for theraindrops is created and set to an emitter node. Properties for the emitter nodeare then set between line 5-14. At the last lines the position for the emitter andall the particles are set to make it look like rain and finally the emitter is addedto the scene.

40

Page 46: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Particle Systems can also be made from scratch with OpenGL ES. As mak-ing a physics engine this require a lot of code and experience and is a largerproject to dig into not covered by this thesis. Many game engines do not comewith a fully integrated particle system and to achieve particle effects with thoseengines a third part library needs to be included. Ricardo Rendon Cepeda [4]has written an good article on how to implement a particle system from scratchwith OpenGL ES for those who are interested.

As mention in section 2.4.2 Sprite Kit also has four more advanced types ofnodes for adding cool and unique effects into your game. When using thesenodes, it is important to keep an eye on performance because these nodes allrequire greater resources. An SKEffectNode allows you to apply special ef-fects to its children nodes. For example, you could use it to modify a sprite’svibrance, hue, exposure, blur, or convert it to black and white.

In our game an SKEffectNode is used to blur the background sprite whena popup is active to achieve an depth of field effect. This special effect is cre-ated with a technology introduced in iOS 5 called Core Image. Core Imageallow you to perform many of the functions that writing custom shaders wouldperform in other game engines.

At the time when this report was written Sprite Kit did not support customrender code for writing special effects. This may not be a big drawback for theaverage game but more advance user will feel that this hit the visual limits ofSprite Kit. For custom rendering we still require an open source framework, orwrite our own game engine on top of OpenGL ES. The last rumors says thatcustom shaders will be supported for Sprite Kit in iOS 8.

However the benefits of using effect nodes is that they are much easier to usethan writing OpenGL and GLSL code. To filtering a SKEffectNode you canapply a Core Image effect to it and all of its children node will also be effected.So you could create a SKEffectNode, add a sprite to it as a child, and it wouldapply the Core Image effect to just that sprite. One simple example how to dothis is shown in listing 4.20 [15]:

41

Page 47: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Listing 4.20: Applying a blur effect

1 SKEffectNode ∗effectNode = [[SKEffectNode alloc] init];2 SKTexture ∗texture =3 [SKTexture textureWithImage:[UIImage imageNamed:@”background”]];4 SKSpriteNode ∗sprite = [SKSpriteNode spriteNodeWithTexture:texture];5 sprite . position = self .view.center ;6 effectNode. filter = [ self blurFilter ];7 effectNode.blendMode = SKBlendModeAdd;8 effectNode.shouldEnableEffects = YES;9 [effectNode addChild:sprite ];

10 [ self addChild:effectNode];1112 //applying blur13 − (CIFilter ∗) blurFilter14 {15 CIFilter ∗ filter = [CIFilter filterWithName:@”CIGaussianBlur”];16 [ filter setDefaults ];17 [ filter setValue :[NSNumber numberWithFloat:20] forKey:@”

inputRadius”];18 return filter ;19 }

At the first 10 lines a effect node and a texture set to a sprite node is created.A filter, some properties and the sprite node are then added to the effect node,which are added to the scene. Core image provides over 100 filters for iOS. Inthe above code, you use the NSString name of the filter to create an instanceof that filter. The actual blur filter is created between line 13-19.

42

Page 48: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Chapter 5

Result

The end result is a simple game made with Sprite Kit running on all iPhonesfrom iPhone 4 and above and all iPads as seen in figure 5.1 and 5.2 .

Figure 5.1: The game running on an iPhone4s

43

Page 49: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Figure 5.2: The game running on an iPad mini

The main character is your hero that you can move through the map and usein battles. The hero can be controlled with touch and he moves towards thetouch location. The goal of the game is to complete the levels on the mapto proceed further in the game. On each level there are an army of variousenemies to defeat before proceed to the next level. The hero gains experienceand can reach higher levels after each fight. After playing a while the herobecome stronger but the hero cannot alone complete all the levels on the map.To assist the hero there are also units to unlock and buy to build up an armyused to defeat the enemies. Some armies can be hard to beat and will requiretactical thinking, strategic movement and a good combination of different units.

I find that the resulting game is well made, good looking and attractive. Theturn-based tactical gameplay will hopefully attract many players that like simi-lar games in that genre. And many of the tools included in Sprite Kit has beenused and tested in our game to achieve the end result.

In larger projects there are always room for further development and muchof the functionality that was desired for our game has not been implementeddue to time limitations. But I think that this game provides a good basis asprototype for further development even if it is not completely finished to belaunched to the app store yet.

To improve the game further to make it ready for a first launch we are planningto add some in-game purchases. This can be items and points that a player

44

Page 50: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

can buy for use within the virtual world to improve the game experience. Thegameplay also need to be improved before the game is ready for a first launch.

45

Page 51: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Chapter 6

Discussion

The main goal with this thesis was to investigate Sprite Kit and how the gameengine helped us during the development process. In the beginning of thisproject I had no previous experience in Objective C. Still I felt that it was easyfor me to jump right into Sprite kit. The game engine is known to be beginner-friendly, with excellent documentation that was all up to date. Sprite Kit takescare of a lot of things that the beginning developer is not aware or capable of,or interesting in doing. This made things it easier in the beginning. To set upa simple starting project that draws a sprite to the scene was easy and requiredjust a few lines of code.

The API was intuitive and easy to use. I liked that all the game objects wasorganized in a tree structure that inherited from SKNode. There was severalother nodes to perform different tasks who felt very straight forward. Also thebuilt in physics engine and particle system was easy to getting started with.Just a small amount of code was needed to provide cool effects to our game,which made it look more polished and professional. Another thing that I foundhelpful with Sprite Kit was the automatic atlasing of our artwork, the art wasjust stored in a folder, that was renamed to folder.atlas and we where done. Inother game engines that I have used before different 3rd party programs hasbeen needed to get texture atlas support and also for particle effects

In our game many of the tools provided by Sprit Kit was used and helpedus to save a lot of time during the development. We would not be where we aretoday if we had to take care of all the low level details and write the game fromscratch using OpenGL ES. In section 4.2.1 and 4.2.2 I compared the code neededto add a sprite with Sprite Kit compared to do the same thing with OpenGl ESand GLKit. As can be seen from these two examples it is far more complex towork with OpenGL ES and GLKit and there are more things to keep in mind.Sprite Kit hides much of the lower level details allowing the programmer to focusmore on the gameplay. Even though I think there are many benefits workingwith Sprite Kit, there are also some drawbacks worth to take into consideration.

46

Page 52: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

I felt when the game project grew larger and I got more knowledge about thegame engine, I discovered some of the limitations of Sprite Kit. First, it was notpossible to access openGL layer to do custom drawing. This can be a hindranceif you are really trying to tweak your graphic or optimize your frame rate. Theyare opening this feature with iOS 8, and it will only work on iOS 8.

The largest issue, however, is that our game code was locked into the iOSEcosystem. Sprite Kit is Apple telling developers to use their native API’s tomake 2D games only available on iOS. SpriteKit currently cannot be exportedto other platforms. This does not mean that our game can not be ported toother popular platforms, but doing so will add cost and time to the project.

Neither I could not find any good way to integrate UIKit components witha Sprit Kit view. UIKit is a apple API that provides the classes to constructuser interface for iOS applications. There was no easy way to use both SpriteKit views and regular UI views. What could be done was to overlap the UIcomponents over a Sprite Kit view, but I felt that this was an ugly solution, asSprite Kit has to handle multiple different scenes. Instead I decided to go onwith SKSpriteNode and SKLabelNode to create the user interface for ourgame.

Many game developers like Kbler [12] and Norton [13] also mention that thephysics system in Sprite Kit is not stable enough. Norton [13] has done sometests where he compare Sprit Kit Physics with a direct implementation ofBox2D. He comes to the conclusion that in terms of simple frame rate per-formance Sprite Kit physics is behind a direct Box2D implementation. Also thelack of access to low level simulation parameters makes it impossible to tuneSprite Kit physics the way you can a direct Box2D implementation.

47

Page 53: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Chapter 7

Conclusion

I think that Sprite Kit provides almost all the tools necessary for creating 2Dmobile games for iOS. I think it is the perfect game engine, especially for be-ginners that want to develop small and medium-sized games, and for creatingsimple game prototypes in no time. Open GL has a notoriously large learningcurve and you have to write a lot of engine code to get a simple game working.For beginning game developer this is a big barrier to entry and therefore SpritKit can be used as an entry point into the world of game development. Forbigger game projects, I guess at some point it will stop being so useful becauseof its limited extensibility. For some game genres, you might want to writecustom OpenGL code, or the physics system will not be stable enough. And ifyou want to make a cross platform game Sprite Kit is not the way to go.

48

Page 54: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Bibliography

[1] Apple (2013). Worldwide Developer Conference WWDC. Website.https://developer.apple.com/wwdc/. Accessed 2014-03-15.

[2] Apple (2013). ”Sprite Kit Programming Guide”https://developer.apple.com/Library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit PG/Introduction/Introduction.html/.Accessed 2014-02-05.

[3] Blow, J.(2004) ”Game Development: Harder Than You Think”,Queue, Vol. 1(10), ss. 2837, February.

[4] Cepeda, R.(2013),”OpenGL ES particle system tutorial series”http://www.raywenderlich.com/37600/opengl-es-particle-system-tutorial-part-1Accessed 2014-05-02.

[5] DiGiovanni, M.(2013), ”iOS 7 Tutorial Series: Introduction to Sprite Kit”http://captechconsulting.com/blog/mark-digiovanni/ios-7-tutorial-series-introduction-sprite-kit Accessed 2014-03-15.

[6] Esoteric Software (2013): Spine 2D animation software for gameshttp://esotericsoftware.com

[7] Itterheim, S.(2013), ”Why Apple Created Sprite Kit And What It MeansFor Cocos2D”http://www.learn-cocos2d.com/2013/06/apple-create-spritekit/Accessed 2014-02-10.

[8] Jingming Xie.(2011), ”The Research on Mobile Game Engine,”in Proc. IEEE Int. Conf. Image Analysis and Signal Processing (IASP), pp.635-639.

[9] Kasavin, G.(2008) ”A Review of Chess by Greg Kasavin”http://wargamerscott.tripod.com/swordandshield/id19.html

[10] Kasurinen, J., Strandn, J. and Smolander K., (2013)”What do Game Developers Expect from Development and Design Tools?”,

49

Page 55: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

Proc. 17th International Conference on Evaluation and Assessment in Soft-ware Engineering (EASE), 14.-16.04.2013, Porto de Galinhas, Brazil.

[11] Khronos Group: OpenGL ES Specification 2.0 (2004)http://www.khronos.org/opengles/.

[12] Kbler, N.(2013), ”iOS 7 Sprite Kit: My Top 5 Pros and Cons”http://www.ymc.ch/en/ios-7-sprite-kit-my-top-5-pros-and-consAccessed 2014-02-10.

[13] Norton, J.(2013), ”Comparing Sprite Kit Physics to Direct Box2D”http://www.element84.com/comparing-sprite-kit-physics-to-direct-box2d.html Accessed 2014-04-10.

[14] Ubisoft (2013),http://might-and-magic.ubi.com/universe/en-US/games/all-games/index.aspx

[15] Wenderlich, R., Berg, M. and Bradley, T., (2013),”iOS Games by Tutorials”Razeware LLC. ISBN 9780989675116

[16] Wenderlich, R.(2014),http://www.raywenderlich.com

[17] Wenderlich, R.(2012),”How To Create A simple 2d iPhone Game with OpenGL ES 2.0 and GLKit- Part 1”http://www.raywenderlich.com/9743/how-to-create-a-simple-2d-iphone-game-with-opengl-es-2-0-and-glkit-part-1Accessed 2014-05-02.

[18] Wilson, G.(2006), ”Off With Their HUDs!: Rethinking the Heads-UpDisplay in Console Game Design”http://www.gamasutra.com/view/feature/2538/off with their huds rethinking .phpAccessed 2014-05-02.

[19] Allewein, C.(2014) ”SKLabelNode replacement to support multiline func-tionality.”,https://github.com/downrightsimple/DSMultilineLabelNode

[20] Hollander, R.(2014) ”A real OpenGL ES 2.0 2D tutorial part 8 RenderingText.”,http://androidblog.reindustries.com/a-real-opengl-es-2-0-2d-tutorial-part-8-rendering-text/

50

Page 56: Institutionen för datavetenskapliu.diva-portal.org/smash/get/diva2:769040/FULLTEXT01.pdf · 2014-12-05 · Sprite Kit is a game engine for making 2D ... ics hardware, support for

På svenska Detta dokument hålls tillgängligt på Internet – eller dess framtida ersättare – under en längre tid från publiceringsdatum under förutsättning att inga extra-ordinära omständigheter uppstår.

Tillgång till dokumentet innebär tillstånd för var och en att läsa, ladda ner, skriva ut enstaka kopior för enskilt bruk och att använda det oförändrat för ickekommersiell forskning och för undervisning. Överföring av upphovsrätten vid en senare tidpunkt kan inte upphäva detta tillstånd. All annan användning av dokumentet kräver upphovsmannens medgivande. För att garantera äktheten, säkerheten och tillgängligheten finns det lösningar av teknisk och administrativ art.

Upphovsmannens ideella rätt innefattar rätt att bli nämnd som upphovsman i den omfattning som god sed kräver vid användning av dokumentet på ovan beskrivna sätt samt skydd mot att dokumentet ändras eller presenteras i sådan form eller i sådant sammanhang som är kränkande för upphovsmannens litterära eller konstnärliga anseende eller egenart.

För ytterligare information om Linköping University Electronic Press se förlagets hemsida http://www.ep.liu.se/ In English The publishers will keep this document online on the Internet - or its possible replacement - for a considerable time from the date of publication barring exceptional circumstances.

The online availability of the document implies a permanent permission for anyone to read, to download, to print out single copies for your own use and to use it unchanged for any non-commercial research and educational purpose. Subsequent transfers of copyright cannot revoke this permission. All other uses of the document are conditional on the consent of the copyright owner. The publisher has taken technical and administrative measures to assure authenticity, security and accessibility.

According to intellectual property law the author has the right to be mentioned when his/her work is accessed as described above and to be protected against infringement.

For additional information about the Linköping University Electronic Press and its procedures for publication and for assurance of document integrity, please refer to its WWW home page: http://www.ep.liu.se/

© [Amaru Ubillus]