I'm currently practicing with particle systems and I was wondering if the following code is the right way to stop and start a particle when a button is tapped?
The code works fine, I touch the start button and the particle starts, I touch the stop button and the particle stops but I'm not sure if removeFromSuperLayer
is the right method to use. As I said, the code does what I need but I just want to make sure that the particle won't keep running in the background even after calling removeFromSuperLayer
and end-up wasting resources.
- (IBAction)stopAnimation:(id)sender
{
[emitterLayer removeFromSuperlayer];
}
- (IBAction)startAnimation:(id)sender
{
[self particle];
}
-(void) particle
{
emitterLayer = [CAEmitterLayer layer];
emitterLayer.emitterPosition = CGPointMake(50 ,50);
emitterLayer.emitterZPosition = 10;
emitterLayer.emitterSize = CGSizeMake(10,10);
emitterLayer.emitterShape = kCAEmitterLayerSphere;
CAEmitterCell *emitterCell = [CAEmitterCell emitterCell];
emitterCell.scale = 0.1;
emitterCell.scaleRange = 0.2;
emitterCell.emissionRange = (CGFloat)M_PI_2;
emitterCell.lifetime = 10;
emitterCell.birthRate = 5;
emitterCell.velocity = 20;
emitterCell.velocityRange = 50;
emitterCell.yAcceleration = 0;
emitterCell.contents = (id)[[UIImage imageNamed:@"particleImage.png"] CGImage];
emitterLayer.emitterCells = [NSArray arrayWithObject:emitterCell];
[self.view.layer addSublayer:emitterLayer];
}
Thanks a lot
A Particle System may stop emitting when its emission module has finished, it has been paused or if the system has been stopped using Stop with the StopEmitting flag.
There's a "play on start" toggle on particle systems. Just turn it off on the ones where you don't want that.
Particle systems are collections of small images that when viewed together form a more complex “fuzzy” object, such as fire, smoke, weather, or fireworks. These complex effects are controlled by specifying the behavior of individual particles using properties such as initial position, velocity, and lifespan.
Basically, the player runs into the coin. Both the coin and the player have a box collider. The particle system should play when the player hits the coins box collider.
You could use a method in which you put the following:
- (void)stopEmitting
{
self.emitterCell.birthRate = 0.0f;
}
With this you should be able to stop the emitting, without having to remove and re-create the layer each time when the start button is pressed.
To start again, simply do:
- (void)startEmitting
{
self.emitterCell.birthRate = <VAlUE HERE (greater than 0)>;
}
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With