Question

hey i am running into a problem. i maade an image object that gets added every 2 seconds by an nstimer. and an update timer updates it so the image goes forward. but it only goes forward until a new one gets added and i can't solve why.

this is the method for adding it.

-(void)addTarget {

UIImage *image1=[UIImage imageNamed:@"enemy.png"];
                 image=[[UIImageView alloc]initWithImage:image1];
                 image.frame=CGRectMake(0,0,50,50);
                 [self.view addSubview:image];
image.center = CGPointMake(150, 150);
image.tag = 1;
[_targets addObject:image];
                     [image release];       
}

self explaining.

-(void) update {
 image.center = CGPointMake(image.center.x+2, image.center.y);

}

and this spawns them.

-(void) spawn {
[self addTarget];
}
Was it helpful?

Solution

Its because you are constantly reallocating the image. You need to be creating a new image1 variable every time and then adding it to an NSMutableArray.

Then in the update method use a for loop to move each image in the array's centre to whatever point.

- (void)update {
    for (UIImage *image in _targets) {
        image.center = CGPointMake(image.center.x+2, image.center.y);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top