
This video is only available to subscribers. Start a subscription today to get access to this and 420 other videos.
Particle Systems
Episode Links
- Episode Source Code
- Fire Effect Tutorial - Ray Wenderlich's blog
- UIEffectDesigner - This app makes it easy to play around with the various settings of an emitter without having to recompile & launch for every tiny change.
- CAEmitterLayer Class Reference
- Particle Playground - This app, available on the Mac App Store, is similar to UIEffectDesigner but offers more values to tweak. Might be worth the $10 if you're planning to tweak particle settings and need a little more control.
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!