After writing Beginning Xcode, I felt something of an obligation to begin writing tutorials for iOS development. The trouble is that it’s sometimes hard to think what to write about outside the context of a book. This weekend I saw someone pose a question about how to add Sprite Kit particle effects to a regular iOS app in Xcode.

[av_notification title=’XCODE 5′ color=’silver’ border=” custom_bg=’#444444′ custom_font=’#ffffff’ size=’large’ icon_select=’yes’ icon=’ue837′ font=’entypo-fontello’]
This article was written for Xcode 5 and has been imported into the new blog and updated slightly.
[/av_notification]

Sprite Kit

If you’re not familiar with Sprite Kit, you’re in for a treat. Sprite Kit is an framework for 2D game development, and it’s Apple’s answer to 2D game frameworks such as Cocos2D. Whilst it might not have the full range of features that Cocos2d has, it’s certainly a powerful and very accessible tool to get started with, and as it’s being developed by Apple, you can can expect a steady improvement in the features available with each successive version of iOS.

Sprite Kit has everything you need to make a everything from a 2d platformer, side scrolling shooter or even the next Angry Birds with it’s powerful built in physics effects. In this tutorial, we’re going to take one of the really neat features, namely particle emitters, and use them to spice up a basic application.

Getting Started

To get things moving, we’ll create a bog standard application and go from there.

  1. Start by opening Xcode and selecting Create a New Project from the Welcome screen, or go to File > New > Project.
  2. Select the “Single View Application” template as shown in Figure 1, and click “Next”.
  3. For the Project Name, I’ve called mine “Particles” but you can name yours whatever you want, and enter a Company Identifier in the reverse domain notation format, so in my case I’ve entered “com.mattknott”. Finally, set Devices to “iPhone” and click “Next”.
  4. Save your project somewhere convenient and click “Create”.
Choosing the Single View Application template
Figure 1: Choosing the Single View Application template

You now have a blank iOS application project, with a single view controller. What you’re going to do is is add a bokeh particle effect to your application to create an animated background. This might not be the most efficient way of doing this but the effect is the important part.

In the second part of this tutorial, you will then create a very different particle effect as you look to display the nation product of Wales, rain.

Choosing a Particle Effect

The great thing about creating a Sprite Kit particle emitter is that it doesn’t require any code to create it, and Xcode let’s you modify it in real-time. Below is a list and description of available effects in action.

[av_slideshow size=’portfolio’ animation=’slide’ autoplay=’false’ interval=’5′ control_layout=”]
[av_slide slide_type=’image’ id=’2032′ video=” mobile_image=” video_ratio=” title=’Bokeh’ link_apply=” link=’lightbox’ link_target=”]
If you’re not familiar with the term, bokeh describes the blurred background effect that can occur in photos.
[/av_slide]
[av_slide slide_type=’image’ id=’2033′ video=” mobile_image=” video_ratio=” title=’Fire’ link_apply=” link=’lightbox’ link_target=”]
The fire emitter does what you would expect, focuses on an intense base fire with flames moving upwards.
[/av_slide]
[av_slide slide_type=’image’ id=’2034′ video=” mobile_image=” video_ratio=” title=’Fireflies’ link_apply=” link=’lightbox’ link_target=”]
The fireflies effect see’s a particle appear and move in a random direction for a short time before disappearing.
[/av_slide]
[av_slide slide_type=’image’ id=’2035′ video=” mobile_image=” video_ratio=” title=’Magic’ link_apply=” link=’lightbox’ link_target=”]
Apart from the default colour, there isn’t a huge difference between fireflies and magic. The behaviour is almost indistinguishable
[/av_slide]
[av_slide slide_type=’image’ id=’2036′ video=” mobile_image=” video_ratio=” title=’Rain’ link_apply=” link=’lightbox’ link_target=”]
Here’s another particle emitter that does what it says on the tin. Statically sized drops falling at differing speeds at an angle.
[/av_slide]
[av_slide slide_type=’image’ id=’2037′ video=” mobile_image=” video_ratio=” title=’Smoke’ link_apply=” link=’lightbox’ link_target=”]
Similar to the fire emitter, the smoke particles cluster at the bottom and rise slowly upwards.
[/av_slide]
[av_slide slide_type=’image’ id=’2038′ video=” mobile_image=” video_ratio=” title=’Snow’ link_apply=” link=’lightbox’ link_target=”]
The last of the elemental effects, snow particles vary in size and fall gently to the ground.
[/av_slide]
[av_slide slide_type=’image’ id=’2039′ video=” mobile_image=” video_ratio=” title=’Spark’ link_apply=” link=’lightbox’ link_target=”]
The most violent of the effects at the start, the sparks emitter resemble sparks coming of a fuse for a stick of dynamite or a firework.
[/av_slide]
[/av_slideshow]

Creating the Particle File

Now that you’ve got an idea what each effect looks like and how the particles behave, let’s create the bokeh particle emitter to create a dynamic animated background.

  1. In Xcode, select File > New > File from the menu bar to create a new file.
  2. Choose “Resources” from the list on the left under iOS, and then “SpriteKit Particle File” as shown in figure 2. Click Next.
  3. Now you need to choose the type of particle emitter you want to create, choose Bokeh from the list and click “Next”.
  4. Finally, Name the new particle file”Bokeh”, accept the suggested save location and click “Create”.
Figure 2: Creating the particle file
Figure 2: Creating the particle file

Instantly you will be treated to the visual spectacle that is your particle emitter.  You will notice that two files were actually added to the project, Bokeh.sks and bokeh.png. The png file is the template for every particle that comes from the emitter.

The next point of interest is the SKNode inspector; this can be accessed by selecting Bokeh.sks in the Project Navigator and then clicking the the third tab in the utility bar (command + option + 7). From here you can adjust the full array of settings for this particle emitter as shown in Figure 3. We’ll use the defaults in this example however, it’s worth noting that you can drastically alter how the particles appear and disappear and what happens to them when they spawn.

Once the particle file is configured, you don’t need to come back to it, all that remains is to add it to the app.

SKView and SKScene

Figure 3: There are a huge number of properties that con be configured for a particle emitter.
Figure 3: There are a huge number of properties that con be configured for a particle emitter.

One of the key concepts you need to get your head around with Sprite Kit is the relationship between the View (SKView) and the Scene (SKScene). The scene is what handles the graphics being rendered on the screen using Sprite Kit, a scene could be a single level, or a loading screen or a “You’re Dead” screen. The view is what you will add to your View Controller to display the scene; a single view can present and number of scenes, which makes it a very flexible element. It’s also worth noting that an SKView isn’t that different from a UIView, it just has a couple of extra methods to allow you to call in and dismiss scenes.

  1. In this tutorial you will be instantiating a regular SKView, but you will need to create a new class file for the scene, so once again, from the menu bar select File > New > File.
  2. Select “Cocoa Touch” from the menu on the left, and then “Objective-C class” and click “Next”.
  3. The Class value will be “BokehScene” and the Subclass of value should be “SKScene”. SKScene is case sensitive and will not autocomplete so make sure you type it correctly.
  4. Click “Next” and finally accept the default save location by clicking “Create”.

The reason that SKScene didn’t autocomplete is that you haven’t imported the Sprite Kit framework into the project yet. Here I’ll show you another neat feature that was new with Xcode 5 / iOS 7: Modules.

I won’t go into too much detail here but basically, modules are a much more efficient way of importing headers for frameworks and classes into your projects. You specifically create a modules import statement by typing @import instead of #import; I say specifically because under the bonnet, your old #import statements are converted to the new modules method at compile time.

The upshot of using modules to import a framework is that you don’t have to go through the old hassles of manually importing the specific framework into the project.

To show you what I mean, go ahead and open the new BokehScene.h file from the Project Navigator.

Under the line #import <UIKit/UIKit.h>, type the following:

@import SpriteKit;

Notice as you type, the code completion does most of the work for you! That’s effectively modules in action, soon you will forget ever having to go into the project settings to add a framework.

You’ve done most of the prep work required for this project, now let’s wrap this up by building the interface and adding a few lines of code to add the particle emitter to the view.

Building the Interface

  1. To get to work on the interface, start by selecting Main.storyboard from the Project Navigator.
  2. Drag a View from the Object Library to the storyboard as shown in figure 4. Position it in the middle of the existing view. The SKView doesn’t have to occupy the whole view, but as I want to use it as a background, it makes sense in this instance.
figure4
Figure 4: Adding an extra UIView to the scene.
  1. Select this View and open the Identity Inspector (command + option + 3).
  2. Change the “Class” value to “SKView” as shown in Figure 5.
Figure 5: Changing the class of the view.
Figure 5: Changing the class of the view.
  1. Now, you need to create an outlet for the SKView so that the view controller can interact with it. The quickest way to do this is to open the Assistant Editor, and then control + drag a connection from the SKView over to the waiting ViewController.m file, between the line @interface ViewController () and @end as shown in Figure 6.
figure6
Figure 6: Dragging an outlet for the view.
  1. When you release the mouse, name the outlet particleBackground as shown in Figure 7 and click “Connect”.
Figure 7: Naming the outlet.
Figure 7: Naming the outlet.
  1. Switch back to the Standard Editor and go back to Main.storyboard file.
  2. Finish the interface by dragging a “Text View” onto the storyboard and resize it so that it resembles Figure 8.
figure8
Figure 8: Adding a UITextView to the scene

[av_notification title=’NOTE’ color=’green’ border=” custom_bg=’#444444′ custom_font=’#ffffff’ size=’large’ icon_select=’yes’ icon=’ue83e’ font=’entypo-fontello’]
When you create the outlet, Xcode will flag it up as an error. This is because the @import SpriteKit statement hasn’t been added to the ViewController.h yet.
[/av_notification]

That’s it for the interface, now you need to write a couple of lines of code to wrap up this first part of the tutorial.

Displaying the Scene and the Particle Emitter

In this part of the tutorial you are going to tie up all of these different parts for the finished effect. The class that does the most work is the BokehScene class; this is where the particle effect is identified and positioned within the scene. Let’s code this first.

Open up BokkeScene.m from the Project Navigator; unlike with some other classes, when you subclass SKScene, Xcode doesn’t give you any starter methods so you’ll need to write the standard SKScene initialiser which is called initWithSize:size. Add the following method between @implementation BokehScene and @end:

-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {
        self.backgroundColor = [SKColor blackColor];
        NSString *emitterPath = [[NSBundle mainBundle] pathForResource:@"Bokeh" ofType:@"sks"];
        SKEmitterNode *bokeh = [NSKeyedUnarchiver unarchiveObjectWithFile:emitterPath];
        bokeh.position = CGPointMake(CGRectGetMidX(self.frame), self.size.height/2);
        bokeh.name = @"particleBokeh";
        bokeh.targetNode = self.scene;
        [self addChild:bokeh];   
    }   
    return self;
}

Let’s break down the method.

Firstly, you set the background to black

self.backgroundColor = [SKColor blackColor];

Then you generate a string with the path to the particle file within the bundle

NSString *emitterPath = [[NSBundle mainBundle] pathForResource:@"Bokeh" ofType:@"sks"];

Next, you use the incredibly useful NSKeyedUnarchiver to decode the physical file and instantiate the SKEmitter object, called bokeh.

SKEmitterNode *bokeh = [NSKeyedUnarchiver unarchiveObjectWithFile:emitterPath];

Finally, perform some configuration to set the position in the centre of the screen, name it and then set the target as the scene. This means that the particle emitter will attach itse;f to the scene, as opposed to a flame you may attach to a rocket.

bokeh.position = CGPointMake(CGRectGetMidX(self.frame), self.size.height/2);
bokeh.name = @"particleBokeh";
bokeh.targetNode = self.scene;

All that remains now is to call the scene from the view controller and the tutorial is complete.

Let’s import Sprite Kit to correct the outstanding error message. Open ViewController.h from the Project Navigator, and below the line #import <UIKit/UIKit.h> type the following:

@import SpriteKit;

Now, open up ViewController.m and under the line #import “ViewController.h” type the following to import the scene you created so that we can instantiate it shortly.

#import "BokehScene.h"

Scroll to the ViewDidLoad method where you will be calling in the SKScene you just created. Beneath the line [super viewDidLoad] you will start writing your code.

Firstly, instantiate a new BokehScene object and set it to the size of the SKView you dragged onto the storyboard and created an outlet for.

BokehScene * scene = [BokehScene sceneWithSize:_particleBackground.bounds.size];

Next, set the scale mode of the scene to Aspect Fill.

scene.scaleMode = SKSceneScaleModeAspectFill;

Finally, tell the SKView you created to display the game scene:

[_particleBackground presentScene:scene];

Your finished ViewDidLoad method will look like this:

- (void)viewDidLoad
{
    [super viewDidLoad];
 
    BokehScene * scene = [BokehScene sceneWithSize:_particleBackground.bounds.size];
    scene.scaleMode = SKSceneScaleModeAspectFill;
    [_particleBackground presentScene:scene];
}

Now, build and run your application to see what happens. If all goes well you should see something like Figure 9.

Figure 9: The finished application in action
Figure 9: The finished application in action