views:

68

answers:

1

I have two UIImageViews moving like sprites on a superview. Each imageview moves properly by itself but when I put both imageviews on the superview at the same time, their individual movement becomes strangely restricted to two different areas of the screen. They will not touch even programmed to the same coordinates.

This is my movement code for the first imageView:

- (void)viewDidLoad {
    [super viewDidLoad];    
    pos = CGPointMake(14.0, 7.0);
    [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}
- (void) onTimer {
    pallone.center = CGPointMake(pallone.center.x+pos.x, pallone.center.y+pos.y);

    if(pallone.center.x > 320 || pallone.center.x < 0)
        pos.x = -pos.x;
    if(pallone.center.y > 480 || pallone.center.y < 0)
        pos.y = -pos.y;
}

and for the second imageview:

- (IBAction)spara{
    cos = CGPointMake(8.0, 4.0);
    [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(inTimer) userInfo:nil repeats:YES];
}
- (void)inTimer{
    bomba.center = CGPointMake(bomba.center.x+pos.x, bomba.center.y+pos.y);

    if(bomba.center.x > 50 || bomba.center.x < 0)
        pos.x = -pos.x;
    if(bomba.center.y > 480 || bomba.center.y < 0)
        pos.y = -pos.y;
}

Why causes this strange behavior?

Thanks for your help. I am a newbie.

A: 

It looks like pos is an instance variable of the class that contains these methods.

Your problem is that you are using the same pos.x and pos.y variables for both imageViews. When one timer method changes pos.x or pos.y for pallone it affects the movement of bomba and vice versa.

The way you handle this is to create a subclass of UIImageView which contains the movement logic. Each imageView will move themselves and maintain its own position data. That way, everything stays compartmentalized.

TechZen
thank you very much, I solved everything !
David Pollak
A check mark would be appreciated.
TechZen