iPhone: Strange Movement of Two UIImageView "Sprites"
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(o开发者_开发知识库nTimer) 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.
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.
精彩评论