Developing Games in iOS Swift With SpriteKit – Part 1

What’s SpriteKit?

SpriteKit is a new framework from iOSonward to make 2d games in iOS and OSX. It comes built-in in Xcode and has fully support for sprites, physics, particle system, filters, video and so on.

SpriteKit uses the traditional game rendering loop where you can render or process the game contents in each frame.

SpriteKit provides a lot of functionalities that are very very useful for games like:

  • Physics simulation
  • Built-in support for complex effects and texture atlas directly in Xcode.
  • Support for cropping and a lot of special effects that can be applied to your content.

 

Why SpriteKit?

SpriteKit is very powerful framework to make 2d games for iOS and OSX. It has a lot of features that you can’t find in other game engines like Cocos2d. It also comes built-in in Xcode and iOS, so Xcode will help you a lot in your game and building scenes and special effects.

 

SpriteKit Pros and Cons:

 

SpriteKit Pros:

  • SpriteKit comes built-in Xcode and iOS so you don’t need to install additional libraries or anything.
  • Written by Apple 🙂 .
  • Supports Particle systems, Special effects, filters and Physics simulation. Also Xcode will help you in this.
  • Very easy to learn specially for beginners.
  • Search for nodes with name or by query.

SpriteKit Cons:

  • You can’t run multiple scenes in the same time unlike Cocos2d where you can push and pop scenes easily.
  • You can’t write custom OpenGL code in your game.
  • For sure, your game will be in iOS only 🙁 . Unlike Cocos2d where you can write games run on iOS and Android.

My Advice:

Someone may ask me and say “Hey dude, I’m confused now, I don’t know which one to use SpriteKit or Cocos2d?”

Look, Each one of them has its pros and cons, so you have to be specific in your requirements to know what’s suitable for you. For example, If you really care about cross platform your game in iOS and Android, I suggest Cocos2d. But If you are a beginner and wanna make fast powerful prototype to your game, I suggest Sprite kit.

 

Deeper into SpriteKit:

SpriteKit contains many important components that you need to know and be aware of them before starting your game.

SpriteKit animations and rendering are performed inside special kind of view called SKView. You have to create this view and place it inside the window. In this case you can render your content to this view.

Your game content in SpriteKit is like most of other game engines is organized to Scenes. Each scene corresponds to a single view for your game. For example you can make a scene for main menu, gameplay, setting, and so on. In SpriteKit the game scene is represented by SKScene. You put your scene contents on it and ask the SKView to present this scene, so all your animation, rendering and per-frame logic will be executed automatically. You can use a single SKView object and switch between scenes. But be aware that the SKView can present only one scene at a time and there is no a stack to push or pop scenes.

The Node Tree:

In your game, the SKScene object acts as the root of the tree nodes (SKNode objects) in your scene which is a descendant of SKNode. The SKNode is the fundamental building block of most SpriteKit objects. It doesn’t draw anything in the view but it applies its properties to all its children. For example, if you have a node and you rotate it, all its children will rotate also.

Although SKNode doesn’t draw anything, the drawable contents are represented by classes which inherit from SKNode. Other subclasses are also don’t draw anything but affect the behavior of their children. Check the table below of SKNode subclasses:

NodeSubclasses

 

Node Actions:

To animate your content and your nodes, you have to use actions. Each action is represented by SKAction object. After creation of SKAction objects, you tell your node to execute these actions by calling runAction: method. Each SKAction object defines which property you want to change in the node, how do you want to change it,  and the duration of changes. For example, you want to move the sprite to the right by 20 px in 2 sec.

So actions can be used to move, rotate, scale, hide, change transparency, resize, colorize, and more. Also actions can be reversed, so you can create the an action from another action by reversing its effect, for example, we can reverse the previous action to make another action to move the sprite to the left by 20 px.

Last thing I want to mention is that you can combine actions together to make:

  • A sequence action => has multiple child actions. Each action in the sequence begins after the previous action ends (sequentially).
  • A group action has multiple child actions. All actions stored in the group begin executing at the same time (simultaneously).
  • A repeating action stores a single child action. When the child action completes, it is restarted.

 

Sprite Node:

SKSpriteNode is a drawable SKNode object that draws textured image or colorized rectangle. SKSpriteNode is your best friend in SpriteKit because you will use it a lot.

 

Getting started:

Now lets get our hands dirty with SpriteKit. We are going to build simple 2d game using SpriteKit and Swift.

Swift is introduced in iOSas a new programming language besides Objective-C. The tutorial is simple to take you quickly from nothing to build a simple 2d game. We are going to make a Flappy Bird style game

Before we start:

  1. Download Xcode 6. Now its beta version and requires at least OSX Mavericks
  2. A cup of tea, coffee or juice to enjoy your time while working in the tutorial.
  3. Download the assets used in our game from Here

 

Open Xcode 6 and create new project. Choose iOS => Application => Game and press Next.

NewProject

 

Then select Swift as our language and SpriteKit as our Game Technology:

Screenshot_7_13_15__12_05_AM

Build and Run, you should see a gray background with label “Hello World”.

Some explanation of generated files:

  1. GameScene.sks => You can assume that it’s the design or the builder of your scene.
  2. GameScene.swift => Where you put all swift code to describe the logic of this scene. In this file you can find the game loop and how we change our contents per frame.
  3. GameViewController.swift  => The first view controller that will displayed to the user and embed the GameScene on it. As we said above, it has the SKView object that will present the first scene of your game.

 

Configure Game to work in Portrait:

Open GameViewController.swift and you will find the overridden function of supportedInterfaceOrientations() , edit the function to be like this:

override func supportedInterfaceOrientations() -> Int {

return Int(UIInterfaceOrientationMask.Portrait.toRaw());
}

 

Here we tell the view controller of SKView that we support only Portrait orientation.

Change GameScene.sks:

Now we will start with changing the design of our scene. That is one of features of Xcode and SpriteKit, where you can design your level before you load it.

If you open the file you will find that the scene size is not correct. Thus we have to update to be 320 x 568 like the size of iPhone in portrait mode.

Open View => Utilities => Show SKNode Inspector. Under the scene properties, change the size to X:320  Y:568

**As you see in the properties, you can change also the background color of your scene.

sceneConfig

 

You can change it to RGB (120, 196, 209)

Now lets write some game logic Swift:

Open GameScene.swift and remove the code inside the functions didMoveToView and touchesBegan so we can start with empty scene.

 

The didMoveToView is called immediately the scene is presented by SKView object.

The touchesBegan tells you when one or more fingers touch down the scene.

Now Build and Run, You should see something like this:

run1

 

Now lets add our bird:

Add the assets that you downloaded in the Xcode project. We will add the bird to our scene from GameScene.sks by dragging the sprite image from Resources to the scene. The sprite will be added with this texture. Also when you open the SKNode Inspector, you will find the properties of this sprite. The Sprite is added as subclass of SKSpriteNode as we mentioned above because its a drawable sprite.

We will change the properties of our sprite like adding a unique name to it. Each sprite you add in the scene should have one if you are going to use it in the game. You can grab a sprite by its unique name.

buildScene

 

As you see in the image, in the right side you can find the properties of SKSpriteNode. We will change the physics of this sprite under the section of Physics Definition to be like this:

physics

 

I hear someone saying  “Hey! Please explain the Physics in SpriteKit!”, so read on!

 

Adding Physics bodies to your scene:

Now for sure in most of games, you need the sprites to interact with each other and cause some collisions. And for sure the action system will not be able to handle something like gravity or forces. Here comes the role of SKPhysicsBody  and attach them to your nodes. Each physics body has its own properties like mass, size , shape and so on.

The SKScene object is responsible for simulating physics on those bodies. Forces like gravity is applied automatically but you can also apply your own forces.

So the SKScene acts as the world of your physics bodies therefore there is a SKPhysicsWorld object attached to the scene. It can be used to configure the world gravity, simulation speed or search for physics bodies.

So now the above image makes sense. We define the shape of the bird body to rectangle and make it dynamic. The dynamic type defines whether the object is affected by collision and other forces or not.

Now open GameScene.swift to do some stuff there. First we need a reference to our bird, we will do this using its unique name like we mentioned earlier:

class GameScene: SKScene {

//This variable is used to know if the game started or not
var gameStarted = false

var bird : SKSpriteNode

init(coder aDecoder: NSCoder!)
{
bird = SKSpriteNode();
super.init(coder: aDecoder);
}

override func didMoveToView(view: SKView) {
/* Setup your scene here */

//Scene physics, create edge loop
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)

//our bird
bird = self.childNodeWithName(“bird”) as SKSpriteNode
bird.physicsBody.density = 1.5;
bird.physicsBody.dynamic = false
}

Notes:

  • The init function has to be overridden and call super to init the variable bird. In Swift you have to init all your properties first
  • We created a body to our scene to prevent the bird from going outside the screen.
  • childNodeWithName is used to get a sprite with a given unique name.
  • as SKSpriteNode is like casting because childNodeWithName return SKNode so we want to cast it to SKSpriteNode
  • I reset the dynamic property again to false so the bird initially will not move (or affected by gravity force) till the user tap on screen to start playing.

Now lets add some action. We will override the touchesBegan and start the game if its not started, otherwise we have to bounce the bird.

func bounceMyBird()
{
let birdDirection = bird.zRotation + M_PI_2
let bounceImpulse: CFloat = 20.5
bird.physicsBody.velocity = CGVectorMake(0, 0);

var vec = CGVectorMake(CGFloat( bounceImpulse*cosf(CFloat(birdDirection))),
CGFloat(
bounceImpulse*sinf(CFloat(birdDirection))));

bird.physicsBody.applyImpulse(vec);
}

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */

for touch : AnyObject in touches
{
if !gameStarted{
gameStarted = true
bird.physicsBody.dynamic = true
}
else
{
// bounce my bird
bounceMyBird();
}
}

}

When the game started, we changed the value of dynamic property of bird to true, so it can be affected with Gravity and impulse.

In bounceMyBird(), we get the birdDirection
and const value of impulse to apply an impulse to the bird in every time the user touch the screen.

Build and run. You should see a bird that can bounce when you touch and fall on the ground by the effect of gravity.

Getting Started Developing Games in iOS Swift With SpriteKit – Part2

BY : Hossam Ghareeb | CATEGORY : News |CATEGORY SLUG: news | Date : 31 August, 2015 | Tags : , ,