Episode #100

Particle Systems

20 minutes
Published on December 19, 2013

This video is only available to subscribers. Get access to this video and 572 others.

In our special 100th episode I dive into a fun little class called CAEmitterLayer. Using this class we can create cool particle effects such as fire, water, smoke, clouds, or a fountain of stars.

Episode Links

Creating a CAEmitterLayer-backed View

All UIKit views are layer-backed, but we need to tell the framework what layer to instantiate. We can do this by defining the layerClass class method.

@implementation MyView

+ (Class)layerClass {
    return [CAEmitterLayer class];
}

@end

Configuring the emitter layer

The emitter layer controls where particles are generated on the screen. We can adjust whether they are generated on a rectangular surface, a sphere, line, or just a single point. We can also control the render modes to control how the particles are drawn & blended together.

- (void)awakeFromNib {
    CAEmitterLayer *emitter = (CAEmitterLayer *)self.layer;
    emitter.emitterShape = kCAEmitterLayerPoint;
    emitter.renderMode = kCAEmitterLayerOldestLast;
    emitter.emitterPosition = CGPointMake(self.frame.size.width / 2 - 40, 300);

    // ...
}

Creating fire particles

Here we will configure an emitter cell to create particles that resemble fire.

    CAEmitterCell *fire = [CAEmitterCell emitterCell];
    fire.contents = (id)[[UIImage imageNamed:@"particle.png"] CGImage];
    fire.contentsRect = CGRectMake(0, 0, 1.0, 1.0);
    fire.birthRate = 13.0;
    fire.lifetime = 5.0;
    fire.velocity = 40;
    fire.velocityRange = 10;

    fire.scale = 1.0;
    fire.scaleRange = 0.1;
    fire.scaleSpeed = 0.2;

    fire.alphaRange = 0.2;
    fire.alphaSpeed = -0.2;

    fire.emissionLongitude = -M_PI_2;
    fire.emissionRange = M_PI / 8;
    fire.color = [[UIColor colorWithRed:0.95 green:0.6 blue:0.2 alpha:0.9] CGColor];
    fire.redRange = 0.1;
    fire.greenSpeed = -0.2;
    fire.blueSpeed = -0.2;

Creating a star fountain

In this example we use a different particle image and a few different properties (including yAcceleration) to create a star fountain effect.

    CAEmitterCell *stars = [CAEmitterCell emitterCell];
    stars.contents = (id)[[UIImage imageNamed:@"star.png"] CGImage];
    stars.contentsRect = CGRectMake(0, 0, 1, 1);
    stars.birthRate = 60;
    stars.lifetime = 10;
    stars.velocity = 200;
    stars.scale = 0.2;
    stars.scaleSpeed = -0.05;
    stars.emissionLongitude = -M_PI_4;
    stars.emissionRange = M_PI /16;
    stars.yAcceleration = 40;
    stars.alphaSpeed = -0.2;

Adding the particles to our emitter layer

In order for these particles to show up we have to tell the layer about our cells:

    emitter.emitterCells = @[stars, fire];

Build & run, and watch our amazing star fountain / fire effect!