Difference between revisions of "An iOS 9 Sprite Kit Particle Emitter Tutorial"

From Techotopia
Jump to: navigation, search
(Particle Emitter Node Properties)
(Using the Particle Emitter Editor)
Line 56: Line 56:
 
   
 
   
  
[[Image:]]
+
[[Image:xcode_7_spritekit_particle_file.png]]
  
 
Figure 70-1
 
Figure 70-1
Line 66: Line 66:
  
  
[[Image:Example.jpg]]
+
[[Image:xcode_6_spritekit_particle_editor.png]]
 
   
 
   
 
Figure 70-2
 
Figure 70-2

Revision as of 19:12, 22 December 2015

PreviousTable of ContentsNext
An iOS 9 Sprite Kit Collision Handling TutorialAn iOS 9 MapKit Flyover Tutorial


<google>BUY_IOS9</google>


In this, the last chapter dedicated to the Sprite Kit framework, the use of the Particle Emitter class and editor to add special effects to Sprite Kit based games will be covered. Having provided an overview of the various elements that make up particle emitter special effects, the SpriteKitDemo application will be extended using particle emitter features to make the balls burst when hit by an arrow. This will also involve the addition of an audio action.


Contents


What is the Particle Emitter?

The Sprite Kit particle emitter is essentially a mechanism designed to add special effects to games. It comprises the SKEmitterNode class and the Particle Emitter Editor bundled with Xcode. A particle emitter special effect begins with an image file that is to represent the particle. The emitter is then responsible for generating multiple instances of the particle on the scene and animating each particle subject to a set of properties. These properties control aspects of the special effect such as the rate of particle generation, the angle and speed of motion of particles, whether or not particles rotate and the way in which the particles blend in with the background.

With some time and experimentation, a wide range of special effects ranging from smoke to explosions can be created using particle emitters.

The Particle Emitter Editor

The Particle Emitter Editor is built into Xcode and provides a visual environment in which to design particle emitter effects. In addition to providing a platform for developing custom effects, the editor also offers a collection of pre-built particle based effects including rain, fire, magic, snow and sparks. These template effects also provide an excellent starting point on which to base other special effects.

Within the editor environment, a canvas displays the current particle emitter configuration. A settings panel allows the various properties of the emitter node to be changed, with each modification reflected in the canvas in real-time, thereby making the task of creating and refining special effects much easier. Once the design of the special effect is complete, the effect is saved in a Sprite Kit particle file. This file actually contains an archived SKEmitterNode object configured to run the particle effects designed in the editor.


The SKEmitterNode Class

The SKEmitterNode is responsible for displaying and running the particle emitter effect within a Sprite Kit game. As with other Sprite Node classes, the SKEmitterNode class has many of the properties and behaviors of other classes in the Sprite Kit family. Generally an SKEmitterNode class is created and initialized with a Sprite Kit particle file created using the Particle Emitter editor. The following code fragment, for example, obtains the path to a specific particle file from the application main bundle and then unarchives the SKEmitterNode instance saved in that particle file. The unarchived node is then configured to appear at a specific position within the current scene before being added to the scene so that it appears within the game:

let burstPath = NSBundle.mainBundle().pathForResource("Burst", 
					ofType: "sks")

let burstNode = NSKeyedUnarchiver.unarchiveObjectWithFile(burstPath!) 
					as! SKEmitterNode

burstNode.position = CGPointMake(100, 400)

self.addChild(burstNode)

Once created, all of the emitter properties that are available within the Particle Emitter Editor are also controllable from within the code allowing the behavior of the effect to be changed in real-time. The following code, for example, adjusts the number of particles the emitter is to emit before ending:

burstEmitter.numParticlesToEmit = 400

In addition, actions may be assigned to particles from within the application code to add additional behavior to a special effect. The particles can, for example, be made to display an animation sequence.

Using the Particle Emitter Editor

By far the easiest and most productive approach to designing particle emitter based special effects is to use the Particle Emitter Editor tool bundled with Xcode. To experience the editor in action, launch Xcode and create a new SpriteKit Game-based application project named ParticleDemo with the Devices and Language menus set to Universal and Swift respectively.

Once the new project has been created, select the File -> New -> File… menu option. In the resulting panel, select the Resource option located beneath the iOS heading in the left hand panel before choosing the SpriteKit Particle File template option as outlined in Figure 70-1:


Xcode 7 spritekit particle file.png

Figure 70-1


Click Next and choose a Particle template on which to base the special effect. For the purposes of this example we will use the Fire template. Click Next and name the file RocketFlame before clicking on Create.

At this point, Xcode will have added two files to the project. One is an image file named spark.png representing the particle and the other is the RocketFlame.sks file containing the particle emitter configuration. Xcode should also have pre-loaded the Particle Emitter Editor panel with the fire effect playing in the canvas as shown in Figure 70 2 (the editor can be accessed at any time by selecting the corresponding sks file in the project navigator panel).


Xcode 6 spritekit particle editor.png

Figure 70-2


The right hand panel of the editor provides access to, and control of, all of the properties associated with the emitter node. To access these property settings, click on the right hand toolbar button in the right hand panel. Much about particle emitter special effects can be learned through experimentation with the particle editor. Before modifying the fire effects in this example, however, it will be helpful to provide an overview of what these properties do.

Particle Emitter Node Properties

The behavior of a particle emitter and associated particles is controlled by a range of property settings. These properties can be summarized as follows:

Background

Though presented as an option within the editor, this is not actually a property of the emitter node. This option is provided so that the appearance of the effect can be tested against different backgrounds. This is of particular importance when the particles are configured to blend with the background. Use this setting to test the particle effects against any background colors the effect is likely to appear with within the game.

Particle Texture

The image file containing the texture that will be used to represent the particles within the emitter.

Particle Birthrate

The birthrate defines the rate at which new particles are emitted by the node. The greater the value the faster new particles are generated, though it is recommended that the minimum number of particles needed to achieve the desired effect be used to avoid performance degradation. The total number of particles to be emitted may also be specified. A value of zero causes particles to be emitted indefinitely. If a limit is specified the node will stop emitting particles when that value is reached.

Particle Life Cycle

The lifetime property controls the length of time in seconds that a particle lives (and is therefore visible) before disappearing from view. The range property may be used to introduce variance in the lifetime from one particle to the next based on a random time value between 0 and the specified range value.

Particle Position Range

The position properties define the location from which particles are created. The X and Y values can be used to declare an area around the center of the node location from which particles will be created randomly.

Angle

The angle at which a newly emitted particle will travel away from the creation point in counterclockwise degrees, where a value of 0 degrees equates to rightward movement. Random variance in direction can be introduced via the range property.

Particle Speed

The speed property specifies the initial speed of the particles at time of creation. The speed can be randomized by specifying a range value.

Particle Acceleration

The acceleration properties control the degree to which a particle accelerates or decelerates after emission in terms of both X and Y directions. <google>BUY_IOS9</google>

Particle Scale

The size of the particles can be configured to change using the scale properties. These settings cause the particles to grow or shrink over the course of their lifetimes. Random resizing behavior can be implemented by specifying a range value. The speed setting controls the speed with which the size changes take place.

Particle Rotation

The rotation properties control the speed and amount of rotation applied to the particles after creation. Values are specified in degrees with positive and negative values correlating to clockwise and counter-clockwise rotation respectively. The speed of rotation may be specified in degrees per second.

Particle Color

The particles created by an emitter can be configured to transition through a range of colors during a lifetime. To add a new color in the lifecycle timeline, click on the color ramp at the location where the color is to change and select a new color. Change an existing color by double clicking on the marker to display the color selection dialog. Figure 70-3, for example, shows a color ramp with three color transitions specified:


Xcode 6 color ramp.png

Figure 70-3


To remove a color from the color ramp, click and drag it downward out of the editor panel.

The color blend settings control the amount by which the colors in the particle’s texture blend with the prevailing color in the color ramp at any given time during the life of the particle. The greater the Factor property, the greater the colors blend, with 0 indicating no blending. The blending factor can be randomized by specifying a range, and the speed at which the blend is performed by adjusting the speed property.

Particle Blend Mode

The Blend Mode property governs the way in which particles blend with other images, colors and graphics in Sprite Kit game scenes. Options available are as follows:

  • Alpha – Blends transparent pixels in the particle with the background.
  • Add – Adds the particle pixels to the corresponding background image pixels.
  • Subtract – Subtracts the particle pixels from the corresponding background image pixels.
  • Multiply - Multiplies the particle pixels by the corresponding background image pixels. Results in a darker particle effect.
  • MultiplyX2 – Creates a darker particle effect than the standard Multiply mode.
  • Screen – Inverts pixels, multiplies and inverts a second time. Results in lighter particle effects.
  • Replace – No blending with the background. Only the particle’s colors are used.

Experimenting with the Particle Emitter Editor

Creating compelling special effects with the particle emitter is largely a case of experimentation. As an example of adapting a template effect for another purpose we will now modify the fire effect in the RocketFlame.sks file so that instead of resembling a camp fire it could instead be attached to the back of a sprite to represent the flame of a rocket launching into space.

Within Xcode, select the previously created RocketFlame.sks file so that it loads into the Particle Emitter Editor. The animation should appear and resemble a camp fire as illustrated in Figure 70 2.

1. The first step in modifying the effect is to change the angle of the flames so that they burn downwards. To achieve this, change the Start property of the Angle setting to 270 degrees. The fire should now be inverted.

2. Change the X value of the Position Range property to 5 so that the flames become narrower and more intense.

3. Increase the Start value of the Speed property to 450.

4. Change the Lifetime start property to 7.

The effect now resembles the flames a user might expect to see shooting out of the back of a rocket against a nighttime sky (Figure 70 4). Note also that the effects of motion of the emitter node may be simulated by clicking and dragging the node around the canvas.


A rocket flame effect using the Xcode 7 particle emitter

Figure 70-4

Bursting a Ball using Particle Emitter Effects

The final task is to update the SpriteKitDemo game so that the balls burst when they are hit by an arrow shot by the archer sprite.

The particles for the bursting ball will be represented by the BallFragment.png file located in the sample code download archive in the sprite_images folder. Open the SpriteKitDemo project within Xcode, locate the BallFragment.png file in a Finder window and drag and drop it onto the list of image sets in the Assets.xcassets file.

Select the File -> New -> File… menu option and, in the resulting panel, select the Resource option located beneath the iOS heading in the left hand panel before choosing the SpriteKit Particle File template option. Click Next and on the template screen select the Spark template. Click Next, name the file BurstParticle and click Create.

The Particle Emitter Editor will appear with the spark effect running. Since the scene on which the effect is going to run has a white background, click on the black swatch next to Background in the SKNode Inspector panel and change the Palette to Apple and the color to White as shown in Figure 70-5:


Xcode 6 change color pallete.png

Figure 70-5 <google>BUY_IOS9</google>

Click on the Particle Texture drop down menu and select the BallFragment image and change the Blend Mode menu to Alpha.

A large number of ball fragments should now be visible all blended with the yellow color specified in the color ramp. Set the Birthrate property to 15 to reduce the number of particles emitted. Click on the yellow marker at the start of the color ramp and change the color to White in the resulting color dialog. The particles should now begin to look like fragments of the ball used in the game.

The fragments of a bursting ball would be expected to originate from any part of the ball. As such the Position Range X and Y values need to match the dimensions of the ball. Set both of these values to 86 accordingly.

Finally, limit the total number of particles by changing the Maximum property in the Particles section to 8.

The burst particle effect is now ready to be incorporated into the game logic.

Adding the Burst Particle Emitter Effect

When an arrow now scores a hit on a ball node, the ball node will be removed from the scene and replaced with a BurstParticle SKEmitterNode instance. To implement this behavior, edit the ArcherScene.swift file and modify the didBeginContact method to add a new method call to extract the SKEmitterNode from the archive in the BurstParticle file, remove the ball node from the scene and replace it at the same position with the emitter:

func didBeginContact(contact: SKPhysicsContact) {
    let firstNode = contact.bodyA.node as! SKSpriteNode
    let secondNode = contact.bodyB.node as! SKSpriteNode

    if (contact.bodyA.categoryBitMask == arrowCategory) && 
		(contact.bodyB.categoryBitMask == ballCategory) {

        let contactPoint = contact.contactPoint
        let contact_y = contactPoint.y
        let target_x = secondNode.position.x
        let target_y = secondNode.position.y
        let margin = secondNode.frame.size.height/2 - 25

        if (contact_y > (target_y - margin)) 
		&& (contact_y < (target_y + margin)) {

             let burstPath = NSBundle.mainBundle().pathForResource(
			"BurstParticle", ofType: "sks")

             if burstPath != nil {
                let burstNode = 
		  NSKeyedUnarchiver.unarchiveObjectWithFile(burstPath!) 
			as! SKEmitterNode
                burstNode.position = CGPointMake(target_x, target_y)
                secondNode.removeFromParent()
                self.addChild(burstNode)
             }
	      score++
        }
    }
}

Compile and run the application. When a ball is hit by an arrow it should now be replaced by the particle emitter effect:


Ios 8 spritekit demo running burst.png

Figure 70-6

Adding an Audio Action

The final effect to add to the game is a bursting sound when an arrow hits the ball. To add this effect we will once again use the Xcode Action Editor. Begin by adding the sound file to the project. This file is named burstsound.mp3 and is located in the audiofiles folder of the book code samples download. Locate this file in a Finder window and drag and drop it onto the Project Navigator panel. In the resulting panel enable the Copy items if needed option and click on Finish.

Within the Project Navigator panel, select the ArcherScene.sks file. From the Object Library panel, locate the Play Sound File Named Action object and drag and drop it onto the timeline so that it is added to the archerNode object:


Xcode 7 spritekit sound action added.png

Figure 70-7

<google>BUY_IOS9</google> Select the new action object in the timeline and use the Attributes Inspector panel to set the Filename property to the burstsound.mp3 file.

Ctrl-click on the sound action and select the Convert to Reference menu option. Name the reference audioAction and click on the Create button. The action has now been saved to the ArcherActions.sks file. Select the object in the timeline, Ctrl-click and select the Delete option to remove it from the scene file.

Finally, modify the didBeginContact method to play the sound action when a ball bursts:

func didBeginContact(contact: SKPhysicsContact) {

    let secondNode = contact.bodyB.node as! SKSpriteNode

    if (contact.bodyA.categoryBitMask == arrowCategory) &&
        (contact.bodyB.categoryBitMask == ballCategory) {

        let contactPoint = contact.contactPoint
        let contact_y = contactPoint.y
        let target_x = secondNode.position.x
        let target_y = secondNode.position.y
        let margin = secondNode.frame.size.height/2 - 25

         if (contact_y > (target_y - margin)) &&
        (contact_y < (target_y + margin)) {
         let burstPath = NSBundle.mainBundle().pathForResource(
        	"BurstParticle", ofType: "sks")

         if burstPath != nil {
            let burstNode =
      NSKeyedUnarchiver.unarchiveObjectWithFile(burstPath!)
        as! SKEmitterNode
            burstNode.position = CGPointMake(target_x, target_y)
            secondNode.removeFromParent()
            self.addChild(burstNode)

            let audioAction = SKAction(named: "audioAction")
            burstNode.runAction(audioAction!)
         }
         score++
        }
    }
}

Run the app one last time and verify that the sound file plays each time a hit is registered on a ball.

Summary

The particle emitter allows special effects to be added to Sprite Kit games. All that is required is an image file to represent the particles and some configuration of the particle emitter properties. Much of this work can be simplified through the use of the Particle Emitter Editor included with Xcode. The editor is supplied with a set of pre-configured special effects such as smoke, fire and rain which can be used as supplied, or modified to meet many special effects needs.


<google>BUY_IOS9</google>



PreviousTable of ContentsNext
An iOS 9 Sprite Kit Collision Handling TutorialAn iOS 9 MapKit Flyover Tutorial