Search code examples
iosimagemovefluid

IOS : Move an image with a timer


Hi, I have a problem, when I click on a button.

I would a timer which stop my code for several milliseconds to create a fluid's movement.

This is my code :

- (IBAction)goRight:(id)sender {
    sprite.image = [UIImage imageNamed:@"sprite_rr.png"];
    [NSThread sleepForTimeInterval:1];
    sprite.center = CGPointMake(sprite.center.x + 5, sprite.center.y);
    sprite.image = [UIImage imageNamed:@"sprite_lr.png"];
}

But this code patient 30 milliseconds then execute directly without waiting.

Can you help me please ? Thanks

PS : Sorry for my bad English ^^


Solution

  • Try:

    - (IBAction)goRight:(id)sender {
        sprite.image = [UIImage imageNamed:@"sprite_rr.png"];
        CGRect frame = sprite.frame;
        frame.origin.x += 5;
        [UIView animateWithDuration:1.0 animations:^{
                [sprite setFrame: frame];
                sprite.image = [UIImage imageNamed:@"sprite_lr.png"];
            }];
    
    }
    

    In order to animate or "move" objects visually, you need to use animateWithDuration: animations: method.

    Edit: Try setting the frame instead of modifying the center.