2

I need to leave a trail with UIView that is animated with CAKeyframeAnimation

Ball * ball = [[Ball alloc]init];
// customized the ball 

CGMutablePathRef path = CGPathCreateMutable();
// filling in the path from points.

CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"position"];
anim.path = path;
anim.rotationMode = kCAAnimationRotateAuto;
anim.repeatCount = HUGE_VALF;
anim.duration = 1.2;
anim.cumulative = YES;
anim.additive = YES;

[ball.layer addAnimation:anim forKey:@"fly"];

Now the Ball.m will have the following Emitter layer:

@implementation TennisBall{

    __weak CAEmitterLayer *emitterLayer;

}


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

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupLayer];
    emitterLayer = [CAEmitterLayer layer];
    emitterLayer.frame = self.bounds;
    emitterLayer.emitterPosition = CGPointMake(160, 240);
    emitterLayer.emitterSize = CGSizeMake(10, 10);
    emitterLayer.renderMode = kCAEmitterLayerAdditive;

    CAEmitterCell *emitterCell = [CAEmitterCell emitterCell];
    emitterCell.birthRate = 1;
    emitterCell.lifetime = 10.0;
    emitterCell.lifetimeRange = 0.5;
    emitterCell.velocity = 20;
    emitterCell.velocityRange = 10;
    emitterCell.emissionRange = 0;
    emitterCell.scaleSpeed = 0.3;
    emitterCell.spin = 0;
    emitterCell.color = [[UIColor colorWithRed:0.8 green:0.4 blue:0.2 alpha:0.1]
                         CGColor];
    emitterCell.contents = (id)[[UIImage imageNamed:@"first.png"] CGImage];
    [emitterCell setName:@"fire"];

    emitterLayer.emitterCells = [NSArray arrayWithObject:emitterCell];

    [self.layer addSublayer:emitterLayer];


   }
 return self;
}

I just need the ball to leave a trail that repeats the path that the ball travels. How do I achieve that?

Stpn
  • 6,202
  • 7
  • 47
  • 94

1 Answers1

0

To make sure the emitter position is correct it the ball layer, You need to make sure emitterPosition same as its anchorPoint.

For example, if anchorPoint is (0,0), then emitterPosition is (0,0). If anchorPoint is (0.5,0.5), and size is (0,0,300,300) then emitterPosition is (150,150)