CAEmitterLayer emits random unwanted particles on touch events

后端 未结 3 1387
灰色年华
灰色年华 2021-02-01 14:01

I\'m trying to set up a CAEmitterLayer to make a confetti effect, and I\'ve run into two issues:

  1. Whenever I set the birthRate on my cell
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-01 14:52

    .h file

     #import 
    
        @interface DWFParticleView : UIView
    
        -(void)setEmitterPositionFromTouch: (CGPoint*)t;
        -(void)setIsEmitting:(BOOL)isEmitting;
    
        @end
    

    .m file

      #import "DWFParticleView.h"
        #import 
    
        @implementation DWFParticleView
        {
            CAEmitterLayer* fireEmitter; //1
        }
    
        -(void)awakeFromNib
        {
            //set ref to the layer
            fireEmitter = (CAEmitterLayer*)self.layer; //2
            //configure the emitter layer
            fireEmitter.emitterPosition = CGPointMake(50, 50);
            fireEmitter.emitterSize = CGSizeMake(10, 10);
    
            CAEmitterCell* fire = [CAEmitterCell emitterCell];
            fire.birthRate = 0;
            fire.lifetime = 1.5;
            fire.lifetimeRange = 0.3;
            fire.color = [[UIColor colorWithRed:255 green:255 blue:255 alpha:0.1] CGColor];
            fire.contents = (id)[[UIImage imageNamed:@"Particles_fire.png"] CGImage];
            [fire setName:@"fire"];
    
            fire.velocity =5;
            fire.velocityRange = 20;
            fire.emissionRange = M_PI_2;
    
            fire.scaleSpeed = 0.1;
            fire.spin = 0.5;
    
            fireEmitter.renderMode = kCAEmitterLayerAdditive;
    
            //add the cell to the layer and we're done
            fireEmitter.emitterCells = [NSArray arrayWithObject:fire];
    
        }
    
        + (Class) layerClass //3
        {
            //configure the UIView to have emitter layer
            return [CAEmitterLayer class];
        }
    
        -(void)setEmitterPositionFromTouch: (CGPoint*)t
        {
            //change the emitter's position
            fireEmitter.emitterPosition = (*t);
        }
    
        -(void)setIsEmitting:(BOOL)isEmitting
        {
            //turn on/off the emitting of particles
            [fireEmitter setValue:[NSNumber numberWithInt:isEmitting?100:0] forKeyPath:@"emitterCells.fire.birthRate"];
        }
    
    
        @end
    

    I used this code for create a custom view and to emit particles on touch

    Here is the call statement for emission of particle on touch

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        CGPoint p =  [[touches anyObject] locationInView:self.view];
         [fireView setEmitterPositionFromTouch: &p];
         [fireView setIsEmitting:YES];
    
    }
    

    may be it will work for you .

提交回复
热议问题