views:

916

answers:

1

I have some code that uses CALayers to have bubbles flowing bottom to top. If the user touches the screen I have some code that replaces the currently running animation with one that has a toPoint where the finger touched down. When the animation switches it causes a flicker on the device (not on the simulator). Any tips on eliminating the flicker would be appreciated! Thanks.

Code for the bubbles flowing up inside the layer itself:

CABasicAnimation *animation = [CABasicAnimationanimationWithKeyPath:@"position"];
[animation setDelegate:self];
CGPoint position = [self position];
NSValue *prevVal = [NSValue valueWithCGPoint:position];
[animation setFromValue:prevVal];
CGPoint toPoint = CGPointMake(position.x,-100);
[animation setToValue:[NSValue valueWithCGPoint:toPoint]];
[animation setDuration:animationDuration];
[self addAnimation:animation forKey:@"flow"];

The code for attracting nearby bubbles to the touch point written in the super layer:

int count = [self.layer.sublayers count];
for(int i = 0; i < count ; i++) {
   CALayer *layer= [self.layer.sublayers objectAtIndex:i];
   CALayer *p = (CALayer*)[layer presentationLayer];
   CGPoint position = [p position];

   if(abs(position.x - touchPoint.x) < 100 && abs(position.y - touchPoint.y) < 100) {

    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setDelegate:self];
    NSValue *prevVal = [NSValue valueWithCGPoint:position];
    [animation setFromValue:prevVal];
    [animation setToValue:[NSValue valueWithCGPoint:touchPoint]];
    [animation setDuration:2.0];
    [animation setTimingFunction:[CAMediaTimingFunction  
            functionWithName:kCAMediaTimingFunctionEaseOut]];
    [layer addAnimation:animation forKey:@"flow"];
   }

}

+1  A: 

Try using a CATransaction lock around your updates to see if that helps. This will prevent the previous animations from changing the position of the layers while you're in the process of updating them with new animations.

In your touch handling method, wrap the animations in a transaction and lock:

[CATransaction lock];
[CATransaction begin];

// update the sublayers with new animations

[CATransaction commit];
[CATransaction unlock];
Jason Foreman