Search code examples
iosobjective-cuikitcalayercabasicanimation

Endless runner imageview animation (No SpriteKit)


Is there a way to animate an UIImageView from right to left without using CABasicAnimation? I'm having troubles with it and I would like to find another way to do it.

The "ground" image its 1200 (width) x 33 (height) and I would like to move it from right to left simulating an endless runner with infinite repetitions.

How can I achieve it without CALayer/CABasicAnimation?.

Thank you!


Solution

  • There's a bunch of methods on UIView that allows any animations, particularly moving views.

    You could move your imageView like this:

    [UIView animateWithDuration:10
                     animations:^{
    
                         yourImageView.frame = frame_you_need;
                     }
                     completion:^(BOOL finished){
    
                        //start from the very beginning
                        //set initial frame to the image view and run the 
                        // animation again
                     }];
    

    so you need two image views. set them start positions, run animations on both, in completion of animation repeat the animation again. that's it

    UPDATE

    I decided to implement this functionality myself. Here's how my animating function looks:

    - (void)runView:(UIView *)aView withStartPosition:(CGPoint)startPosition
    {
    aView.center = startPosition;
    
    [UIView animateWithDuration:3
                          delay:0
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{
    
                         CGPoint newPosition = CGPointMake(aView.center.x + aView.frame.size.width, aView.center.y);
                         aView.center = newPosition;
                     }
                     completion:^(BOOL finished){
    
                         [self runView:aView withStartPosition:startPosition];
    
                     }];
    }
    

    The project demonstrating this functionality is here: Github